Skip to content

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

:sparkles: Improve mobile search result navigation and highlighting https://github.com/siyuan-note/siyuan/issues/20834

Daniel22a29c52f167
diff --git a/app/src/mobile/editor.scroll.test.ts b/app/src/mobile/editor.scroll.test.ts
index 12347588eb..c0562fba13 100644
--- a/app/src/mobile/editor.scroll.test.ts
+++ b/app/src/mobile/editor.scroll.test.ts
@@ -55,6 +55,7 @@ const setup = (legacy?: IScrollAttr, encrypted = false) => {
const attributes: Array<(ready: boolean) => void> = [];
const toolbar = {value: "Document"};
const bottomBacklink = {close: (): Promise<void> | undefined => undefined, updates: 0};
+ let clearedSearchHighlights = 0;
const window: any = {siyuan: {
storage: {positions: {root: clone(legacy)}},
config: {editor: {dynamicLoadBlocks: 128, databaseAttrShow: true}, fileTree: {}}, mobile: {},
@@ -139,6 +140,7 @@ const setup = (legacy?: IScrollAttr, encrypted = false) => {
"./util/mobileTopBar": {restoreMobileTopBarLayout: noop},
"./util/MobileEditorDialog": {closeMobileEditorSheets: noop},
"./util/openReference": {invalidateMobileReferenceOpen: noop},
+ "./menu/searchHighlight": {clearMobileSearchHighlight: () => { clearedSearchHighlights++; }},
"./util/bottomBacklink": {closeMobileBottomBacklinkPanel: () => bottomBacklink.close(),
updateMobileBottomBacklinkPanel: () => { bottomBacklink.updates++; return Promise.resolve(); }},
});
@@ -155,6 +157,7 @@ const setup = (legacy?: IScrollAttr, encrypted = false) => {
}, false, true);
});
return {load, switchRow, requests, rendered, constructed, window, presentation, attributes, bottomBacklink,
+ get clearedSearchHighlights() { return clearedSearchHighlights; },
get docRequest() { return requests.filter(item => item.url === "/api/filetree/getDoc").at(-1)?.data; }};
};
@@ -164,6 +167,7 @@ test("mobile document loading waits for bottom backlink input before reusing the
const pending = new Promise<void>(resolve => { saved = resolve; });
state.bottomBacklink.close = () => pending;
const loading = state.load();
+ assert.equal(state.clearedSearchHighlights, 1);
assert.equal(state.requests.length, 0);
state.bottomBacklink.close = () => undefined;
saved();
diff --git a/app/src/mobile/editor.ts b/app/src/mobile/editor.ts
index 460d737e2a..81f1191371 100644
--- a/app/src/mobile/editor.ts
+++ b/app/src/mobile/editor.ts
@@ -25,6 +25,7 @@ import {invalidateTrackedRanges} from "../protyle/util/trackedRange";
import {getActiveMobileSecondaryEditor} from "./util/secondaryEditors";
import {closeMobileEditorSheets} from "./util/MobileEditorDialog";
import {invalidateMobileReferenceOpen} from "./util/openReference";
+import {clearMobileSearchHighlight} from "./menu/searchHighlight";
import {closeAVCellEditor} from "../protyle/render/av/cellEditor";
import {clearDatabaseRowNavigation} from "../protyle/render/av/databaseRowNavigation";
import {prepareDatabaseAttributePanel} from "../protyle/render/av/attributePanel";
@@ -76,6 +77,7 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[
onFailure?: (invalid?: boolean, editorUnchanged?: boolean) => void, keepPanels = false,
waitForDatabaseAttributes = false) => {
invalidateMobileReferenceOpen();
+ clearMobileSearchHighlight();
const closing = closeMobileEditorSheets() || closeMobileBottomBacklinkPanel();
if (closing) {
void closing.then(() => {
@@ -382,6 +384,7 @@ export const openMobileFileById = (app: App, id: string, action: TProtyleAction[
scrollPosition?: ScrollLogicalPosition, notebookId?: string,
afterOpen?: (protyle: IProtyle) => void, forceReload = false,
waitForDatabaseAttributes = false): Promise<boolean> => {
+ clearMobileSearchHighlight();
const closing = closeMobileEditorSheets();
if (closing) {
return closing.then(() => openMobileFileById(app, id, action, scrollPosition, notebookId, afterOpen,
diff --git a/app/src/mobile/menu/search.test.ts b/app/src/mobile/menu/search.test.ts
new file mode 100644
index 0000000000..a2c6ebe118
--- /dev/null
+++ b/app/src/mobile/menu/search.test.ts
@@ -0,0 +1,69 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isVariableStatement, ScriptTarget, transpileModule} from "typescript";
+
+const source = createSourceFile("search.ts", readFileSync("src/mobile/menu/search.ts", "utf8"), ScriptTarget.ES2021, true);
+const declarations = source.statements.filter(isVariableStatement).flatMap(statement =>
+ Array.from(statement.declarationList.declarations));
+const declaration = declarations.find(item => item.name.getText(source) === "openSearchResult");
+const compiled = transpileModule(`let searchOpenVersion = 0; const ${declaration.getText(source)};
+ globalThis.open = openSearchResult;`, {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
+
+const setup = () => {
+ const folds: Array<(zoomIn: boolean) => void> = [];
+ const opens: Array<{id: string, actions: string[], notebookID: string, after: (protyle: unknown) => void}> = [];
+ const highlights: Array<{protyle: unknown, id: string, keywords: string[]}> = [];
+ const context = {
+ open: undefined as (app: unknown, target: unknown) => void,
+ window: {siyuan: {mobile: {}}},
+ Constants: {CB_GET_ALL: "all", CB_GET_HL: "highlight", CB_GET_CONTEXT: "context", CB_GET_ROOTSCROLL: "root-scroll"},
+ getKeysByLiElement: (target: {keywords: string[]}) => [...target.keywords],
+ checkFold: (_id: string, after: (zoomIn: boolean) => void) => folds.push(after),
+ closePanel() {},
+ openMobileFileById: (_app: unknown, id: string, actions: string[], position: string, notebookID: string,
+ after: (protyle: unknown) => void) => {
+ assert.equal(position, "start");
+ opens.push({id, actions: [...actions], notebookID, after});
+ return Promise.resolve(true);
+ },
+ highlightMobileSearchResult: (protyle: unknown, id: string, keywords: string[]) => {
+ highlights.push({protyle, id, keywords: [...keywords]});
+ },
+ };
+ runInNewContext(compiled, context);
+ return {open: context.open, folds, opens, highlights};
+};
+
+test("mobile search opens ordinary and folded results before highlighting their actual matched words", () => {
+ for (const folded of [false, true]) {
+ const state = setup();
+ const target = {dataset: {nodeId: "hit", notebookId: "encrypted-box"}, keywords: ["Actual", "matched text"]};
+ state.open({}, target);
+ target.keywords = ["changed after click"];
+ state.folds[0](folded);
+ assert.equal(state.opens.length, 1);
+ assert.equal(state.opens[0].id, "hit");
+ assert.equal(state.opens[0].notebookID, "encrypted-box");
+ assert.deepEqual(state.opens[0].actions, folded ? ["all", "highlight"] : ["highlight", "context", "root-scroll"]);
+ assert.equal(state.highlights.length, 0);
+ const editor = {id: "opened-editor"};
+ state.opens[0].after(editor);
+ assert.deepEqual(state.highlights, [{protyle: editor, id: "hit", keywords: ["Actual", "matched text"]}]);
+ }
+});
+
+test("mobile search ignores out-of-order fold checks and callbacks from an older result", () => {
+ const state = setup();
+ const first = {dataset: {nodeId: "first"}, keywords: ["one"]};
+ const second = {dataset: {nodeId: "second"}, keywords: ["two"]};
+ state.open({}, first);
+ state.open({}, second);
+ state.folds[1](false);
+ state.folds[0](true);
+ assert.deepEqual(state.opens.map(item => item.id), ["second"]);
+ state.open({}, first);
+ state.opens[0].after({});
+ assert.equal(state.highlights.length, 0);
+});
diff --git a/app/src/mobile/menu/search.ts b/app/src/mobile/menu/search.ts
index a03d4953ba..7023d39d20 100644
--- a/app/src/mobile/menu/search.ts
+++ b/app/src/mobile/menu/search.ts
@@ -15,7 +15,7 @@ import {getIconByType} from "../../editor/getIcon";
import {preventScroll} from "../../protyle/scroll/preventScroll";
import {openModel} from "./model";
import {getDisplayName, getNotebookIcon, getNotebookName, isEncryptedBox, movePathTo, pathPosix} from "../../util/pathName";
-import {getKeyByLiElement, initCriteriaMenu, moreMenu} from "../../search/menu";
+import {getKeyByLiElement, getKeysByLiElement, initCriteriaMenu, moreMenu} from "../../search/menu";
import {isDisabledFeature, isInIOS, setStorageVal} from "../../protyle/util/compatibility";
import {escapeHtml} from "../../util/escape";
import {unicode2Emoji} from "../../emoji";
@@ -45,6 +45,32 @@ import {
toggleSearchHistory
} from "../../search/toggleHistory";
import {cancelSearchRequest, scheduleSearchRequest} from "../../search/request";
+import {highlightMobileSearchResult} from "./searchHighlight";
+
+let searchOpenVersion = 0;
+
+const openSearchResult = (app: App, target: HTMLElement) => {
+ const id = target.dataset.nodeId;
+ const keywords = getKeysByLiElement(target);
+ const notebookId = target.dataset.notebookId;
+ const version = ++searchOpenVersion;
+ if (window.siyuan.mobile.editor?.protyle) {
+ preventScroll(window.siyuan.mobile.editor.protyle);
+ }
+ checkFold(id, zoomIn => {
+ if (version !== searchOpenVersion) {
+ return;
+ }
+ void openMobileFileById(app, id, zoomIn ? [Constants.CB_GET_ALL, Constants.CB_GET_HL] :
+ [Constants.CB_GET_HL, Constants.CB_GET_CONTEXT, Constants.CB_GET_ROOTSCROLL], "start", notebookId,
+ protyle => {
+ if (version === searchOpenVersion) {
+ highlightMobileSearchResult(protyle, id, keywords);
+ }
+ });
+ });
+ closePanel();
+};
const replace = (element: Element, config: Config.IUILayoutTabSearchConfig, isAll: boolean) => {
if (window.siyuan.isPublish) {
@@ -207,7 +233,7 @@ ${getFileTreeIconHTML(getNotebookIcon(item.box), "notebook", "b3-list-item__grap
newData = childItem;
}
}
- resultHTML += `<div style="padding-left: 36px" data-type="search-item" class="b3-list-item" data-node-id="${childItem.id}">
+ resultHTML += `<div style="padding-left: 36px" data-type="search-item" class="b3-list-item" data-node-id="${childItem.id}" data-notebook-id="${childItem.box}">
<svg class="b3-list-item__graphic"><use xlink:href="#${getIconByType(childItem.type)}"></use></svg>
${unicode2Emoji(childItem.ial.icon, "b3-list-item__graphic", true)}
<span class="b3-list-item__text${childItem.type === "NodeAttributeView" ? " search__av-content" : ""}">${childItem.content}</span>
@@ -225,7 +251,7 @@ ${childItem.tag ? `<span class="b3-list-item__meta b3-list-item__meta--ellipsis"
newData = item;
}
}
- resultHTML += `<div class="b3-list-item b3-list-item--two" data-type="search-item" data-node-id="${item.id}">
+ resultHTML += `<div class="b3-list-item b3-list-item--two" data-type="search-item" data-node-id="${item.id}" data-notebook-id="${item.box}">
<div class="b3-list-item__first">
<svg class="b3-list-item__graphic"><use xlink:href="#${getIconByType(item.type)}"></use></svg>
${unicode2Emoji(item.ial.icon, "b3-list-item__graphic", true)}
@@ -753,13 +779,7 @@ const initSearchEvent = (app: App, element: Element, config: Config.IUILayoutTab
} else if (target.getAttribute("data-type") === "search-item") {
const id = target.getAttribute("data-node-id");
if (id) {
- if (window.siyuan.mobile.editor?.protyle) {
- preventScroll(window.siyuan.mobile.editor.protyle);
- }
- checkFold(id, (zoomIn) => {
- openMobileFileById(app, id, zoomIn ? [Constants.CB_GET_ALL] : [Constants.CB_GET_HL, Constants.CB_GET_CONTEXT, Constants.CB_GET_ROOTSCROLL], "start");
- });
- closePanel();
+ openSearchResult(app, target);
} else {
if (!target.classList.contains("b3-list-item--focus")) {
element.querySelector("#searchAssetList .b3-list-item--focus").classList.remove("b3-list-item--focus");
diff --git a/app/src/mobile/menu/searchHighlight.dom.test.ts b/app/src/mobile/menu/searchHighlight.dom.test.ts
new file mode 100644
index 0000000000..3f9e73c697
--- /dev/null
+++ b/app/src/mobile/menu/searchHighlight.dom.test.ts
@@ -0,0 +1,202 @@
+import * as assert from "node:assert/strict";
+import {execFile} from "node:child_process";
+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";
+import {tmpdir} from "node:os";
+import * as path from "node:path";
+import {test} from "node:test";
+import {promisify} from "node:util";
+import {ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = async (source: string) => {
+ const check: typeof assert = require("node:assert/strict");
+ const api = new Function("Constants", "isInEmbedBlock", "restoreTableVirtualizationDOM", source +
+ "\nreturn {highlightMobileSearchResult, clearMobileSearchHighlight, getSearchMarkRanges, searchMarkRender};")(
+ {TIMEOUT_COUNT: 1000, TIMEOUT_TRANSITION: 20},
+ (element: HTMLElement) => !!element.closest('[data-type="NodeBlockQueryEmbed"]'), () => {}) as
+ typeof import("./searchHighlight") & typeof import("../../protyle/render/searchMarkRender");
+ const pause = () => new Promise(resolve => setTimeout(resolve, 80));
+ const cssHighlights = CSS.highlights;
+ const setCSSSupport = (supported: boolean) => Object.defineProperty(CSS, "highlights", {
+ value: supported ? cssHighlights : undefined, configurable: true,
+ });
+ const content = document.createElement("div");
+ content.className = "protyle-content";
+ content.style.cssText = "height:300px;width:320px;overflow:auto;line-height:24px;font-size:16px";
+ document.body.append(content);
+ const title = document.createElement("div");
+ title.textContent = "Title needle";
+ const wysiwyg = document.createElement("div");
+ content.append(title, wysiwyg);
+ const protyle = {
+ element: content, contentElement: content, wysiwyg: {element: wysiwyg},
+ block: {rootID: "doc"}, title: {editElement: title, element: title},
+ highlight: {mark: new Highlight(), markHL: new Highlight(), ranges: [], rangeIndex: 0,
+ styleElement: document.createElement("style")},
+ } as unknown as IProtyle;
+ protyle.highlight.styleElement.dataset.uuid = "mobile-test";
+ Object.assign(window, {siyuan: {mobile: {editor: {protyle}}}});
+ const setup = (html: string) => {
+ api.clearMobileSearchHighlight();
+ setCSSSupport(true);
+ getSelection().removeAllRanges();
+ wysiwyg.innerHTML = html + '<div style="height:400px"></div>';
+ content.scrollTop = 0;
+ protyle.block.rootID = "doc";
+ window.siyuan.mobile.editor.protyle = protyle;
+ };
+ const inView = (range: Range, container: HTMLElement = content) => {
+ const rect = range.getBoundingClientRect();
+ const viewport = container.getBoundingClientRect();
+ check.ok(rect.top >= viewport.top && rect.bottom <= viewport.bottom,
+ `match ${rect.top}-${rect.bottom} outside viewport ${viewport.top}-${viewport.bottom}`);
+ };
+ const highlighted = () => protyle.highlight.ranges[protyle.highlight.rangeIndex];
+ const longText = "line<br>".repeat(80);
+
+ // 共用的桌面端高亮仍按块选择当前命中,并排除工具栏文字和跨越排除节点的匹配。
+ setup('<div data-node-id="other">needle</div><div data-node-id="hit">nee<strong>dle</strong>' +
+ '<span class="excluded">needle</span>end</div>');
+ await new Promise<void>(resolve => api.searchMarkRender(protyle, ["needle", "needleend"], "hit", resolve,
+ {rootElement: wysiwyg, excludeSelector: ".excluded"}));
+ check.equal(protyle.highlight.ranges.length, 2);
+ check.equal(highlighted().toString(), "needle");
+ check.ok(wysiwyg.querySelector('[data-node-id="hit"]').contains(highlighted().startContainer));
+ protyle.highlight.mark.clear();
+ protyle.highlight.markHL.clear();
+ protyle.highlight.ranges = [];
+
+ // 长段落中跨文本节点的命中按阅读顺序定位,列表外相同词和隐藏文字不参与。
+ setup('<div data-node-id="other">needle</div><div data-node-id="hit">' +
+ '<span style="display:none">needle</span>' + longText + "nee<strong>dle</strong> second</div>");
+ const before = wysiwyg.innerHTML;
+ api.highlightMobileSearchResult(protyle, "hit", ["second", "needle"]);
+ await pause();
+ check.equal(highlighted().toString(), "needle");
+ check.equal(protyle.highlight.markHL.size, 1);
+ check.equal(protyle.highlight.mark.size, 1);
+ inView(highlighted());
+ check.equal(wysiwyg.innerHTML, before);
+ check.equal(getSelection().toString(), "");
+
+ // 同一编辑器再次打开其他命中块时清理旧标记,并保留没有正文命中的块级位置。
+ api.highlightMobileSearchResult(protyle, "other", ["needle"]);
+ await pause();
+ check.equal(protyle.highlight.ranges.length, 1);
+ check.equal(highlighted().startContainer.parentElement.dataset.nodeId, "other");
+ content.scrollTop = 120;
+ api.highlightMobileSearchResult(protyle, "hit", ["attribute-only"]);
+ await pause();
+ check.equal(protyle.highlight.ranges.length, 0);
+ check.equal(content.scrollTop, 120);
+ api.highlightMobileSearchResult(protyle, "hit", []);
+ check.equal(protyle.highlight.mark.size, 0);
+
+ // 聚焦后的折叠块与普通命中块使用同一高亮流程;嵌入的同 ID 内容不得抢走定位。
+ setup('<div data-type="NodeBlockQueryEmbed"><div data-node-id="hit">needle</div></div>' +
+ '<div data-node-id="hit">' + longText + "needle</div>");
+ api.highlightMobileSearchResult(protyle, "hit", ["needle"]);
+ await pause();
+ check.equal(highlighted().startContainer.parentElement.closest('[data-type="NodeBlockQueryEmbed"]'), null);
+ inView(highlighted());
+
+ // 标题命中只定位标题,不能把正文的相同词当成当前结果。
+ api.highlightMobileSearchResult(protyle, "doc", ["needle"]);
+ await pause();
+ check.ok(title.contains(highlighted().startContainer));
+ inView(highlighted());
+
+ // 代码渲染替换节点后重新计算命中范围,并处理代码容器的横向和纵向滚动。
+ setup('<div data-node-id="code" class="code-block"><div class="protyle-action">needle</div>' +
+ '<div class="hljs" style="overflow:auto;max-height:140px"><div contenteditable="false">needle</div>' +
+ '<div contenteditable="true" style="white-space:pre">' + "line\n".repeat(60) +
+ "x".repeat(150) + "needle</div></div></div>");
+ api.highlightMobileSearchResult(protyle, "code", ["needle"]);
+ await pause();
+ const code = wysiwyg.querySelector<HTMLElement>('[contenteditable="true"]');
+ code.innerHTML = code.textContent.replace("needle", '<span class="hljs-string">nee</span>dle');
+ await pause();
+ check.equal(highlighted().toString(), "needle");
+ check.equal(protyle.highlight.ranges.length, 1);
+ inView(highlighted(), code.parentElement);
+ const rect = highlighted().getBoundingClientRect();
+ const viewport = code.parentElement.getBoundingClientRect();
+ check.ok(rect.left >= viewport.left && rect.right <= viewport.right);
+
+ // 旧 WebView 使用真实原生选区,正文内容和节点结构不变。
+ setup('<div data-node-id="hit">' + longText + "nee<strong>dle</strong></div>");
+ setCSSSupport(false);
+ const legacyHTML = wysiwyg.innerHTML;
+ api.highlightMobileSearchResult(protyle, "hit", ["needle"]);
+ await pause();
+ check.equal(getSelection().toString(), "needle");
+ inView(getSelection().getRangeAt(0));
+ check.equal(wysiwyg.innerHTML, legacyHTML);
+ api.clearMobileSearchHighlight();
+ check.equal(getSelection().toString(), "");
+
+ // 快速切换和已失效的文档渲染不能再滚动或添加高亮。
+ for (const invalidate of [() => api.clearMobileSearchHighlight(), () => { protyle.block.rootID = "new-doc"; },
+ () => { window.siyuan.mobile.editor.protyle = {} as IProtyle; }]) {
+ setup('<div data-node-id="hit">' + longText + "needle</div>");
+ api.highlightMobileSearchResult(protyle, "hit", ["needle"]);
+ invalidate();
+ await pause();
+ check.equal(protyle.highlight.markHL.size, 0);
+ check.equal(content.scrollTop, 0);
+ }
+ setup('<div data-node-id="hit">' + longText + "needle</div>");
+ api.highlightMobileSearchResult(protyle, "hit", ["needle"]);
+ await pause();
+ content.dispatchEvent(new Event("beforeinput", {bubbles: true}));
+ check.equal(protyle.highlight.markHL.size, 0);
+ const scrollTop = content.scrollTop;
+ wysiwyg.querySelector('[data-node-id="hit"]').prepend(document.createTextNode("needle"));
+ await pause();
+ check.equal(content.scrollTop, scrollTop);
+ check.equal(protyle.highlight.markHL.size, 0);
+
+ api.clearMobileSearchHighlight();
+ setCSSSupport(true);
+ content.remove();
+ return "Mobile search highlighting cases passed";
+};
+
+test("mobile search highlights and scrolls real text ranges without changing document content", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+}, async () => {
+ const compile = (source: string) => transpileModule(source.replace(/^import [\s\S]*?;\r?\n/gm, "")
+ .replace(/^export /gm, ""), {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
+ const source = compile(readFileSync(path.join(__dirname, "../../protyle/render/searchMarkRender.ts"), "utf8")) +
+ "\n" + compile(readFileSync(path.join(__dirname, "searchHighlight.ts"), "utf8"));
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-mobile-search-test-"));
+ const script = path.join(temporary, "run.cjs");
+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");
+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});
+app.commandLine.appendSwitch("disable-gpu");
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});
+ try {
+ await win.loadURL("about:blank");
+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(
+ `const __name = value => value; (${browserCases.toString()})(${JSON.stringify(source)})`)}));
+ win.destroy();
+ app.exit(0);
+ } catch (error) {
+ console.error(error);
+ win.destroy();
+ app.exit(1);
+ }
+});`, "utf8");
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],
+ {env, timeout: 40000, windowsHide: true});
+ assert.match(result.stdout, /Mobile search highlighting cases passed/);
+ } finally {
+ assert.equal(path.dirname(path.resolve(temporary)), path.resolve(tmpdir()));
+ assert.ok(path.basename(temporary).startsWith("siyuan-mobile-search-test-"));
+ rmSync(temporary, {recursive: true, force: true});
+ }
+});
diff --git a/app/src/mobile/menu/searchHighlight.ts b/app/src/mobile/menu/searchHighlight.ts
new file mode 100644
index 0000000000..ad58a8005e
--- /dev/null
+++ b/app/src/mobile/menu/searchHighlight.ts
@@ -0,0 +1,118 @@
+import {Constants} from "../../constants";
+import {getSearchMarkRanges, isSupportCSSHL, searchMarkRender} from "../../protyle/render/searchMarkRender";
+import {isInEmbedBlock} from "../../protyle/util/hasClosest";
+import {restoreTableVirtualizationDOM} from "../../protyle/util/tableVirtualizationDOM";
+
+let disposeHighlight: () => void;
+
+export const clearMobileSearchHighlight = () => {
+ disposeHighlight?.();
+ disposeHighlight = undefined;
+};
+
+const scrollToMatch = (protyle: IProtyle, range: Range) => {
+ // 先调整代码块、表格等内部滚动容器,再让命中文字进入编辑器视口。
+ let element = range.startContainer.parentElement;
+ while (element && protyle.contentElement.contains(element)) {
+ const style = getComputedStyle(element);
+ const rect = element.getBoundingClientRect();
+ const match = range.getBoundingClientRect();
+ if (/auto|scroll/.test(style.overflowX) && element.scrollWidth > element.clientWidth) {
+ element.scrollLeft += match.left - rect.left - element.clientWidth / 2;
+ }
+ if (element === protyle.contentElement ||
+ /auto|scroll/.test(style.overflowY) && element.scrollHeight > element.clientHeight) {
+ element.scrollTop += match.top - rect.top - element.clientHeight / 2 + match.height / 2;
+ }
+ if (element === protyle.contentElement) {
+ break;
+ }
+ element = element.parentElement;
+ }
+};
+
+export const highlightMobileSearchResult = (protyle: IProtyle, id: string, keywords: string[]) => {
+ clearMobileSearchHighlight();
+ if (keywords.length === 0) {
+ return;
+ }
+ const target = Array.from(protyle.wysiwyg.element.querySelectorAll<HTMLElement>(`[data-node-id="${id}"]`))
+ .find(element => !isInEmbedBlock(element)) ||
+ (id === protyle.block.rootID ? protyle.title?.editElement : undefined);
+ if (!target) {
+ return;
+ }
+ restoreTableVirtualizationDOM(target);
+ const rootID = protyle.block.rootID;
+ let disposed = false;
+ let version = 0;
+ let timer: number;
+ let selectionRange: Range;
+ let currentRange: Range;
+ const isCurrent = () => !disposed && target.isConnected &&
+ window.siyuan.mobile.editor?.protyle === protyle && protyle.block.rootID === rootID;
+ const scroll = () => {
+ if (isCurrent() && currentRange?.toString()) {
+ scrollToMatch(protyle, currentRange);
+ }
+ };
+ const render = () => {
+ const renderVersion = ++version;
+ clearTimeout(timer);
+ timer = window.setTimeout(() => {
+ if (!isCurrent()) {
+ return;
+ }
+ const ranges = getSearchMarkRanges(target, keywords,
+ '.protyle-action, .protyle-attr, .protyle-icons, .hljs > [contenteditable="false"], ' +
+ ".av__views, .av__selection-toolbar, .av__calendar-toolbar, .av__row--footer")
+ .sort((a, b) => a.startIndex - b.startIndex)
+ .map(match => match.range)
+ .filter(range => Array.from(range.getClientRects()).some(rect => rect.width > 0 && rect.height > 0));
+ currentRange = ranges[0];
+ if (isSupportCSSHL()) {
+ searchMarkRender(protyle, keywords, 0, scroll, {
+ rootElement: target,
+ ranges,
+ isValid: () => isCurrent() && renderVersion === version,
+ });
+ } else if (currentRange) {
+ // 旧 WebView 使用原生选区标出当前命中,不向可编辑正文插入标记。
+ const selection = getSelection();
+ selection.removeAllRanges();
+ selection.addRange(currentRange);
+ selectionRange = currentRange;
+ scroll();
+ }
+ });
+ };
+ // 代码高亮和异步内容渲染可能替换文本节点,短时间内重新计算范围和位置。
+ const mutationObserver = new MutationObserver(render);
+ mutationObserver.observe(target, {childList: true, characterData: true, subtree: true});
+ const resizeObserver = new ResizeObserver(scroll);
+ resizeObserver.observe(protyle.wysiwyg.element);
+ const stopObserving = () => {
+ mutationObserver.disconnect();
+ resizeObserver.disconnect();
+ };
+ const observerTimer = window.setTimeout(stopObserving, Constants.TIMEOUT_COUNT);
+ const events = ["pointerdown", "touchstart", "keydown", "beforeinput", "wheel"];
+ const dispose = () => {
+ disposed = true;
+ clearTimeout(timer);
+ clearTimeout(observerTimer);
+ stopObserving();
+ events.forEach(event => protyle.element.removeEventListener(event, clearMobileSearchHighlight, true));
+ protyle.highlight.mark?.clear();
+ protyle.highlight.markHL?.clear();
+ protyle.highlight.ranges = [];
+ protyle.highlight.rangeIndex = 0;
+ const selection = getSelection();
+ if (selectionRange && selection.rangeCount && selection.getRangeAt(0) === selectionRange) {
+ selection.removeAllRanges();
+ }
+ };
+ disposeHighlight = dispose;
+ events.forEach(event => protyle.element.addEventListener(event, clearMobileSearchHighlight, {capture: true, passive: true}));
+ render();
+};
diff --git a/app/src/protyle/render/searchMarkRender.ts b/app/src/protyle/render/searchMarkRender.ts
index cd2e26d56c..e2d3221ba3 100644
--- a/app/src/protyle/render/searchMarkRender.ts
+++ b/app/src/protyle/render/searchMarkRender.ts
@@ -2,6 +2,56 @@ import {Constants} from "../../constants";
import {isInEmbedBlock} from "../util/hasClosest";
import {restoreTableVirtualizationDOM} from "../util/tableVirtualizationDOM";
+export const getSearchMarkRanges = (rootElement: HTMLElement, keys: string[], excludeSelector?: string) => {
+ const textNodes: Node[] = [];
+ const textNodesSize: number[] = [];
+ const excludedTextNodeCounts: number[] = [];
+ let currentSize = 0;
+ let excludedTextNodeCount = 0;
+ const treeWalker = document.createTreeWalker(rootElement, NodeFilter.SHOW_TEXT);
+ let currentNode = treeWalker.nextNode();
+ while (currentNode) {
+ textNodes.push(currentNode);
+ currentSize += currentNode.textContent.length;
+ textNodesSize.push(currentSize);
+ if (excludeSelector && currentNode.parentElement?.closest(excludeSelector)) {
+ excludedTextNodeCount++;
+ }
+ excludedTextNodeCounts.push(excludedTextNodeCount);
+ currentNode = treeWalker.nextNode();
+ }
+ const text = rootElement.textContent;
+ const matches: {range: Range, startIndex: number}[] = [];
+ keys.forEach(key => {
+ if (!key) {
+ return;
+ }
+ let startIndex = 0;
+ let currentNodeIndex = 0;
+ while ((startIndex = text.indexOf(key, startIndex)) !== -1) {
+ const endIndex = startIndex + key.length;
+ while (currentNodeIndex < textNodes.length && textNodesSize[currentNodeIndex] <= startIndex) {
+ currentNodeIndex++;
+ }
+ const startNodeIndex = currentNodeIndex;
+ while (currentNodeIndex < textNodes.length && textNodesSize[currentNodeIndex] < endIndex) {
+ currentNodeIndex++;
+ }
+ const excludedCountBefore = startNodeIndex ? excludedTextNodeCounts[startNodeIndex - 1] : 0;
+ if (excludedTextNodeCounts[currentNodeIndex] === excludedCountBefore) {
+ const range = document.createRange();
+ range.setStart(textNodes[startNodeIndex], startIndex -
+ (startNodeIndex ? textNodesSize[startNodeIndex - 1] : 0));
+ range.setEnd(textNodes[currentNodeIndex], endIndex -
+ (currentNodeIndex ? textNodesSize[currentNodeIndex - 1] : 0));
+ matches.push({range, startIndex});
+ }
+ startIndex = endIndex;
+ }
+ });
+ return matches;
+};
+
export const searchMarkRender = (protyle: IProtyle, keys: string[], hlId?: string | number, cb?: () => void,
options?: {
rootElement?: HTMLElement,
@@ -37,27 +87,7 @@ export const searchMarkRender = (protyle: IProtyle, keys: string[], hlId?: strin
hlBlockElement = protyle.title.element;
}
- // 准备一个数组来保存所有文本节点
- const textNodes: Node[] = [];
- const textNodesSize: number[] = [];
- const excludedTextNodeCounts: number[] = [];
- let currentSize = 0;
- let excludedTextNodeCount = 0;
const rootElement = options?.rootElement || protyle.contentElement;
-
- const treeWalker = document.createTreeWalker(rootElement, NodeFilter.SHOW_TEXT);
- let currentNode = treeWalker.nextNode();
- while (currentNode) {
- textNodes.push(currentNode);
- currentSize += currentNode.textContent.length;
- textNodesSize.push(currentSize);
- if (options?.excludeSelector && currentNode.parentElement?.closest(options.excludeSelector)) {
- excludedTextNodeCount++;
- }
- excludedTextNodeCounts.push(excludedTextNodeCount);
- currentNode = treeWalker.nextNode();
- }
-
const text = rootElement.textContent;
const rangeIndexes: { range: Range, startIndex: number, isCurrent: boolean }[] = [];
if (options?.ranges) {
@@ -73,48 +103,10 @@ export const searchMarkRender = (protyle: IProtyle, keys: string[], hlId?: strin
rangeIndexes.push({range, startIndex: prefix.toString().length, isCurrent});
});
} else if (keys && keys.length > 0) {
- keys.forEach(key => {
- if (!key) {
- return;
- }
- let startIndex = 0;
- let endIndex = 0;
- let currentNodeIndex = 0;
- while ((startIndex = text.indexOf(key, startIndex)) !== -1) {
- const range = new Range();
- endIndex = startIndex + key.length;
- try {
- while (currentNodeIndex < textNodes.length && textNodesSize[currentNodeIndex] <= startIndex) {
- currentNodeIndex++;
- }
- const startNodeIndex = currentNodeIndex;
- let currentTextNode = textNodes[currentNodeIndex];
-
- while (currentNodeIndex < textNodes.length && textNodesSize[currentNodeIndex] < endIndex) {
- currentNodeIndex++;
- }
- currentTextNode = textNodes[currentNodeIndex];
- const excludedCountBefore = startNodeIndex ? excludedTextNodeCounts[startNodeIndex - 1] : 0;
- if (excludedTextNodeCounts[currentNodeIndex] > excludedCountBefore) {
- startIndex = endIndex;
- continue;
- }
- range.setStart(textNodes[startNodeIndex], startIndex -
- (startNodeIndex ? textNodesSize[startNodeIndex - 1] : 0));
- range.setEnd(currentTextNode, endIndex - (currentNodeIndex ? textNodesSize[currentNodeIndex - 1] : 0));
-
- let isCurrent = false;
- if (!isSetHL && hlBlockElement && hlBlockElement.contains(currentTextNode)) {
- isSetHL = true;
- isCurrent = true;
- }
-
- rangeIndexes.push({range, startIndex, isCurrent});
- } catch (e) {
- console.error("searchMarkRender error:", e);
- }
- startIndex = endIndex;
- }
+ getSearchMarkRanges(rootElement, keys, options?.excludeSelector).forEach(match => {
+ const isCurrent = !isSetHL && !!hlBlockElement?.contains(match.range.endContainer);
+ isSetHL = isSetHL || isCurrent;
+ rangeIndexes.push({...match, isCurrent});
});
}