Skip to content

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

:bug: Locate database search preview matches https://github.com/siyuan-note/siyuan/issues/20019

Daniel5eac7f061018
diff --git a/app/src/protyle/render/av/locate.ts b/app/src/protyle/render/av/locate.ts
index c79e0c26d1..eaf5f3b053 100644
--- a/app/src/protyle/render/av/locate.ts
+++ b/app/src/protyle/render/av/locate.ts
@@ -208,7 +208,12 @@ export const setAVLocateRequest = (blockElement: HTMLElement, request: IAVLocate
};
const getAVLocateRequest = (blockElement: HTMLElement) => {
- return locateRequests.get(blockElement);
+ const request = locateRequests.get(blockElement);
+ if (request?.isValid && !request.isValid()) {
+ locateRequests.delete(blockElement);
+ return;
+ }
+ return request;
};
const clearAVLocateRequest = (blockElement: HTMLElement, request: IAVLocateRequest) => {
diff --git a/app/src/protyle/render/av/locateState.ts b/app/src/protyle/render/av/locateState.ts
index 9850f928c3..950747cbda 100644
--- a/app/src/protyle/render/av/locateState.ts
+++ b/app/src/protyle/render/av/locateState.ts
@@ -11,6 +11,7 @@ export interface IAVLocateRequest {
previousViewID?: string;
messageShown?: boolean;
located?: boolean;
+ isValid?: () => boolean;
}
export const locateRequests = new WeakMap<HTMLElement, IAVLocateRequest>();
diff --git a/app/src/protyle/render/searchMarkRender.ts b/app/src/protyle/render/searchMarkRender.ts
index 75df5cbb61..b87d770ba7 100644
--- a/app/src/protyle/render/searchMarkRender.ts
+++ b/app/src/protyle/render/searchMarkRender.ts
@@ -7,11 +7,15 @@ export const searchMarkRender = (protyle: IProtyle, keys: string[], hlId?: strin
rootElement?: HTMLElement,
currentElement?: Element,
excludeSelector?: string,
+ isValid?: () => boolean,
}) => {
if (!isSupportCSSHL() || ((!keys || keys.length === 0) && !hlId)) {
return;
}
setTimeout(() => {
+ if (options?.isValid && !options.isValid()) {
+ return;
+ }
restoreTableVirtualizationDOM(protyle.wysiwyg.element);
protyle.highlight.markHL.clear();
protyle.highlight.mark.clear();
@@ -103,16 +107,10 @@ export const searchMarkRender = (protyle: IProtyle, keys: string[], hlId?: strin
// 没有匹配到关键字,但是有高亮块时,需将其添加进去
if (!isSetHL && hlBlockElement) {
- const startIndex = text.indexOf(hlBlockElement.textContent);
- if (startIndex > -1) {
- const range = new Range();
- let currentNodeIndex = 0;
- while (textNodes.length && textNodesSize[currentNodeIndex] <= startIndex) {
- currentNodeIndex++;
- }
- range.setStart(textNodes[currentNodeIndex], 0);
- rangeIndexes.push({range, startIndex, isCurrent: true});
- }
+ const range = new Range();
+ range.selectNodeContents(hlBlockElement);
+ range.collapse(true);
+ rangeIndexes.push({range, startIndex: text.indexOf(hlBlockElement.textContent), isCurrent: true});
}
rangeIndexes.sort((b, a) => {
diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.ts
index 11123e2172..f9565ba5db 100644
--- a/app/src/protyle/util/onGet.ts
+++ b/app/src/protyle/util/onGet.ts
@@ -56,6 +56,7 @@ export const onGet = (options: {
updateReadonly?: boolean,
scrollPosition?: ScrollLogicalPosition,
afterCB?: () => void,
+ afterAVRender?: () => void | Promise<void>,
dataDocType?: string,
isValid?: () => boolean,
focusAfterZoom?: boolean,
@@ -156,6 +157,7 @@ export const onGet = (options: {
isSyncing: options.data.data.isSyncing,
refreshHeadingNumbers,
afterCB: options.afterCB,
+ afterAVRender: options.afterAVRender,
isValid: options.isValid,
scrollPosition: options.scrollPosition,
focusAfterZoom: options.focusAfterZoom,
@@ -176,6 +178,7 @@ export const onGet = (options: {
isSyncing: options.data.data.isSyncing,
refreshHeadingNumbers,
afterCB: options.afterCB,
+ afterAVRender: options.afterAVRender,
isValid: options.isValid,
scrollPosition: options.scrollPosition,
focusAfterZoom: options.focusAfterZoom,
@@ -209,6 +212,7 @@ export const onGet = (options: {
isSyncing: options.data.data.isSyncing,
refreshHeadingNumbers,
afterCB: options.afterCB,
+ afterAVRender: options.afterAVRender,
isValid: options.isValid,
scrollPosition: options.scrollPosition,
focusAfterZoom: options.focusAfterZoom,
@@ -242,6 +246,7 @@ const setHTML = (options: {
scrollPosition?: ScrollLogicalPosition,
refreshHeadingNumbers?: boolean,
afterCB?: () => void,
+ afterAVRender?: () => void | Promise<void>,
focusAfterZoom?: boolean,
suppressFocus?: boolean,
isValid?: () => boolean,
@@ -382,7 +387,14 @@ const setHTML = (options: {
}
processRender(protyle.wysiwyg.element);
highlightRender(protyle.wysiwyg.element);
- avRender(protyle.wysiwyg.element, protyle);
+ const avRendering = avRender(protyle.wysiwyg.element, protyle);
+ if (options.afterAVRender) {
+ void avRendering.then(() => {
+ if (!options.isValid || options.isValid()) {
+ return options.afterAVRender();
+ }
+ }).catch(error => console.error(error));
+ }
blockRender(protyle, protyle.wysiwyg.element);
renderHeadingNumbers(protyle);
if (options.refreshHeadingNumbers) {
diff --git a/app/src/search/avPreview.test.ts b/app/src/search/avPreview.test.ts
new file mode 100644
index 0000000000..976465b6be
--- /dev/null
+++ b/app/src/search/avPreview.test.ts
@@ -0,0 +1,174 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const compiled = transpileModule(readFileSync("src/search/avPreview.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+
+const setup = () => {
+ let resolveFetch: (value: unknown) => void;
+ let resolveRender: () => void;
+ let renderedCallback: (data: unknown) => void;
+ let current = true;
+ let itemVisible = true;
+ let fieldVisible = true;
+ const field = {};
+ const item = {querySelector: () => fieldVisible ? field : null};
+ const block = {isConnected: true, removeAttribute() {}, querySelector: () => itemVisible ? item : null};
+ const protyle = {element: {isConnected: true}, wysiwyg: {element: {querySelector: () => block}}};
+ const requests: {itemID: string, keyID?: string, viewID?: string, select?: boolean, persistView?: boolean}[] = [];
+ const fetches: unknown[] = [];
+ const api = {} as typeof import("./avPreview");
+ const window = {siyuan: {isPublish: false}};
+ runInNewContext(compiled, {
+ exports: api,
+ window,
+ require: (name: string) => ({
+ "../util/fetch": {fetchSyncPost: (_url: string, data: unknown) => {
+ fetches.push(data);
+ return new Promise(resolve => { resolveFetch = resolve; });
+ }},
+ "../protyle/render/av/locate": {setAVLocateRequest: (_block: unknown, request: typeof requests[number]) => {
+ assert.equal(_block, block);
+ requests.push(request);
+ }},
+ "../protyle/render/av/render": {avRender: (_block: unknown, _protyle: unknown, callback: typeof renderedCallback) => {
+ assert.equal(_block, block);
+ assert.equal(_protyle, protyle);
+ renderedCallback = callback;
+ return new Promise<void>(resolve => { resolveRender = resolve; });
+ }},
+ })[name],
+ });
+ return {
+ api, protyle, block, item, field, requests, fetches, window,
+ options: {protyle: protyle as unknown as IProtyle, id: "database", method: 0,
+ keywords: ["needle"], isCurrent: () => current},
+ setCurrent(value: boolean) { current = value; },
+ setItemVisible(value: boolean) { itemVisible = value; },
+ setFieldVisible(value: boolean) { fieldVisible = value; },
+ async fetched(data: unknown = {itemID: "row", matchedKeyID: "field", viewID: "other-view"}) {
+ resolveFetch({code: 0, data});
+ await new Promise(resolve => setImmediate(resolve));
+ },
+ rendered(status = "visible") {
+ renderedCallback({target: {status}});
+ resolveRender();
+ },
+ };
+};
+
+test("database preview loads the matched item before exposing its field and keeps the current view", async () => {
+ const state = setup();
+ let completed = false;
+ const pending = state.api.locateSearchAVPreview(state.options).then(result => {
+ completed = true;
+ return result;
+ });
+ await state.fetched();
+ assert.equal(completed, false);
+ assert.equal(state.requests.length, 1);
+ assert.equal(state.requests[0].itemID, "row");
+ assert.equal(state.requests[0].keyID, "field");
+ assert.equal(state.requests[0].viewID, undefined);
+ assert.equal(state.requests[0].persistView, false);
+ assert.equal(state.requests[0].select, false);
+ state.rendered();
+ const result = await pending;
+ assert.equal(result.rootElement, state.block);
+ assert.equal(result.currentElement, state.field);
+ assert.equal(result.unavailable, false);
+});
+
+test("database preview rejects stale fetches and detached blocks before locating", async () => {
+ for (const detach of [false, true]) {
+ const state = setup();
+ const pending = state.api.locateSearchAVPreview(state.options);
+ if (detach) {
+ state.block.isConnected = false;
+ } else {
+ state.setCurrent(false);
+ }
+ await state.fetched();
+ assert.equal(await pending, undefined);
+ assert.equal(state.requests.length, 0);
+ }
+});
+
+test("database preview rejects a render completed after another search", async () => {
+ const state = setup();
+ const pending = state.api.locateSearchAVPreview(state.options);
+ await state.fetched();
+ state.setCurrent(false);
+ state.rendered();
+ assert.equal(await pending, undefined);
+});
+
+test("database preview preserves filtered and hidden groups and falls back to the row for hidden fields", async () => {
+ for (const status of ["filtered", "groupHidden", "itemNotFound", "visible"]) {
+ const state = setup();
+ state.setItemVisible(status === "visible");
+ state.setFieldVisible(false);
+ const pending = state.api.locateSearchAVPreview(state.options);
+ await state.fetched();
+ state.rendered(status);
+ const result = await pending;
+ assert.equal(result.unavailable, status !== "visible");
+ assert.equal(result.currentElement, status === "visible" ? state.item : undefined);
+ }
+});
+
+test("database preview skips absent value matches, unsupported search methods and publish mode", async () => {
+ const state = setup();
+ const pending = state.api.locateSearchAVPreview(state.options);
+ await state.fetched(null);
+ assert.equal(await pending, undefined);
+ assert.equal(state.requests.length, 0);
+ for (const method of [2, 4]) {
+ assert.equal(await state.api.locateSearchAVPreview({...state.options, method}), undefined);
+ }
+ state.window.siyuan.isPublish = true;
+ assert.equal(await state.api.locateSearchAVPreview(state.options), undefined);
+ assert.equal(state.fetches.length, 1);
+});
+
+test("preview request identity isolates editors, repeated block searches and closed previews", () => {
+ const state = setup();
+ const first = state.api.beginSearchPreviewRequest(state.protyle as unknown as IProtyle);
+ const other = {element: {isConnected: true}};
+ const independent = state.api.beginSearchPreviewRequest(other as unknown as IProtyle);
+ assert.equal(first(), true);
+ const second = state.api.beginSearchPreviewRequest(state.protyle as unknown as IProtyle);
+ assert.equal(first(), false);
+ assert.equal(second(), true);
+ assert.equal(independent(), true);
+ state.protyle.element.isConnected = false;
+ assert.equal(second(), false);
+});
+
+test("stale preview locate requests cannot scroll, highlight or show filtered-item messages", () => {
+ const source = transpileModule(readFileSync("src/protyle/render/av/locate.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ const requests = new WeakMap();
+ const api = {} as typeof import("../protyle/render/av/locate");
+ runInNewContext(source, {
+ exports: api,
+ require: (name: string) => name === "./locateState" ? {locateRequests: requests} : {},
+ });
+ const block = {isConnected: true} as HTMLElement;
+ const data = {target: {status: "filtered", itemID: "row"}} as IAV;
+ const request = {itemID: "row", isValid: () => false};
+ for (const action of [
+ () => api.getAVLocateParams(block),
+ () => api.prepareAVLocate(block, data, {virtualData: {}}),
+ () => api.finishAVLocate(block, {} as IProtyle, data),
+ ]) {
+ api.setAVLocateRequest(block, request);
+ action();
+ assert.equal(requests.has(block), false);
+ }
+});
diff --git a/app/src/search/avPreview.ts b/app/src/search/avPreview.ts
new file mode 100644
index 0000000000..901c0bf624
--- /dev/null
+++ b/app/src/search/avPreview.ts
@@ -0,0 +1,59 @@
+import {fetchSyncPost} from "../util/fetch";
+import {avRender} from "../protyle/render/av/render";
+import {setAVLocateRequest} from "../protyle/render/av/locate";
+
+const previewRequests = new WeakMap<IProtyle, symbol>();
+
+export const beginSearchPreviewRequest = (protyle: IProtyle) => {
+ const token = Symbol();
+ previewRequests.set(protyle, token);
+ return () => previewRequests.get(protyle) === token && protyle.element.isConnected;
+};
+
+export const locateSearchAVPreview = async (options: {
+ protyle: IProtyle,
+ id: string,
+ method: number,
+ keywords: string[],
+ isCurrent: () => boolean,
+}): Promise<{rootElement: HTMLElement, currentElement?: HTMLElement, unavailable: boolean} | undefined> => {
+ const blockElement = options.protyle.wysiwyg.element.querySelector<HTMLElement>(
+ `.av[data-node-id="${options.id}"]`);
+ if (!blockElement || !options.isCurrent() || ![0, 1, 3].includes(options.method) ||
+ !options.keywords?.length || window.siyuan.isPublish) {
+ return;
+ }
+ const response = await fetchSyncPost("/api/av/getAttributeViewSearchTarget", {
+ id: options.id,
+ keywords: options.keywords,
+ });
+ if (!options.isCurrent() || !blockElement.isConnected || response.code !== 0 || !response.data) {
+ return;
+ }
+ const target = response.data;
+ // 搜索预览沿用当前视图,只定位条目,不写入视图配置或改变编辑选区。
+ setAVLocateRequest(blockElement, {
+ itemID: target.itemID,
+ keyID: target.matchedKeyID,
+ select: false,
+ highlight: true,
+ persistView: false,
+ isValid: options.isCurrent,
+ });
+ blockElement.removeAttribute("data-render");
+ let rendered: IAV;
+ await avRender(blockElement, options.protyle, data => {
+ rendered = data;
+ });
+ if (!options.isCurrent() || !blockElement.isConnected) {
+ return;
+ }
+ const item = blockElement.querySelector<HTMLElement>(
+ `.av__row[data-id="${target.itemID}"], .av__gallery-item[data-id="${target.itemID}"], .av__calendar-item[data-id="${target.itemID}"]`);
+ return {
+ rootElement: blockElement,
+ currentElement: item?.querySelector<HTMLElement>(
+ `[data-col-id="${target.matchedKeyID}"], [data-field-id="${target.matchedKeyID}"]`) || item || undefined,
+ unavailable: rendered?.target?.status !== "visible" || !item,
+ };
+};
diff --git a/app/src/search/util.ts b/app/src/search/util.ts
index ed23d95cd6..0dfe4617d2 100644
--- a/app/src/search/util.ts
+++ b/app/src/search/util.ts
@@ -50,7 +50,7 @@ import {getUnRefList, openSearchUnRef, unRefMoreMenu} from "./unRef";
import {getDefaultSubType, getDefaultType} from "./getDefault";
import {isSupportCSSHL, searchMarkRender} from "../protyle/render/searchMarkRender";
import {saveKeyList, toggleAssetHistory, toggleReplaceHistory, toggleSearchHistory} from "./toggleHistory";
-import {highlightById} from "../util/highlightById";
+import {highlightById, scrollCenter} from "../util/highlightById";
import {getSelectionOffset} from "../protyle/util/selection";
import {getHostCapabilities} from "../util/hostCapabilities";
import {electronUndo} from "../protyle/undo";
@@ -67,6 +67,7 @@ import {
syncSearchConfigHPath,
} from "./config";
import {beginSearchPathRequest, invalidateSearchPathRequests, refreshCurrentSearchPath} from "./path";
+import {beginSearchPreviewRequest, locateSearchAVPreview} from "./avPreview";
const persistSearchConfig = (config: Config.IUILayoutTabSearchConfig) => {
window.siyuan.storage[Constants.LOCAL_SEARCHDATA] = resolvePersistedSearchConfig(
@@ -1238,7 +1239,14 @@ const renderNextSearchMark = (options: {
});
if (currentRange) {
if (!currentRange.toString()) {
- highlightById(options.edit.protyle, options.id, "center");
+ const itemElement = hasClosestByClassName(currentRange.startContainer, "av__row") ||
+ hasClosestByClassName(currentRange.startContainer, "av__gallery-item") ||
+ hasClosestByClassName(currentRange.startContainer, "av__calendar-item");
+ if (itemElement) {
+ scrollCenter(options.edit.protyle, itemElement, "center");
+ } else {
+ highlightById(options.edit.protyle, options.id, "center");
+ }
} else {
scrollToCurrent(options.edit.protyle.contentElement, currentRange, contentRect);
}
@@ -1263,17 +1271,15 @@ const renderNextSearchMark = (options: {
}
};
-let articleId: string;
-
export const getArticle = (options: {
id: string,
config?: Config.IUILayoutTabSearchConfig,
edit: Protyle
value?: string,
}) => {
- articleId = options.id;
+ const isCurrent = beginSearchPreviewRequest(options.edit.protyle);
checkFold(options.id, (zoomIn) => {
- if (articleId !== options.id) {
+ if (!isCurrent()) {
return;
}
options.edit.protyle.scroll.lastScrollTop = 0;
@@ -1285,7 +1291,7 @@ export const getArticle = (options: {
docInfoParam.notebook = options.edit.protyle.notebookId;
}
fetchPost("/api/block/getDocInfo", docInfoParam, (response) => {
- if (articleId !== options.id) {
+ if (!isCurrent()) {
return;
}
const getDocParam: FileTreeGetDocRequestInput = {
@@ -1302,7 +1308,7 @@ export const getArticle = (options: {
getDocParam.notebook = options.edit.protyle.notebookId;
}
fetchPost("/api/filetree/getDoc", getDocParam, getResponse => {
- if (articleId !== options.id) {
+ if (!isCurrent()) {
return;
}
options.edit.protyle.query = {
@@ -1317,22 +1323,52 @@ export const getArticle = (options: {
}
onGet({
updateReadonly: true,
+ isValid: isCurrent,
data: getResponse,
protyle: options.edit.protyle,
action: zoomIn ? [Constants.CB_GET_ALL, Constants.CB_GET_HTML] : [Constants.CB_GET_HTML],
- afterCB() {
+ afterAVRender: async () => {
if (getResponse.code !== 0) {
return;
}
+ let preview: Awaited<ReturnType<typeof locateSearchAVPreview>>;
+ try {
+ preview = await locateSearchAVPreview({
+ protyle: options.edit.protyle,
+ id: options.id,
+ method: options.config?.method ?? 0,
+ keywords: getResponse.data.keywords,
+ isCurrent,
+ });
+ } catch (error) {
+ console.error(error);
+ }
+ if (!isCurrent()) {
+ return;
+ }
+ if (preview?.unavailable) {
+ options.edit.protyle.highlight.mark.clear();
+ options.edit.protyle.highlight.markHL.clear();
+ options.edit.protyle.highlight.ranges = [];
+ return;
+ }
const contentRect = options.edit.protyle.contentElement.getBoundingClientRect();
if (isSupportCSSHL()) {
let observer: ResizeObserver;
searchMarkRender(options.edit.protyle, getResponse.data.keywords, options.id, () => {
const highlightKeys = () => {
+ if (!isCurrent()) {
+ observer?.disconnect();
+ return;
+ }
const currentRange = options.edit.protyle.highlight.ranges[options.edit.protyle.highlight.rangeIndex];
if (options.edit.protyle.highlight.ranges.length > 0 && currentRange) {
if (!currentRange.toString()) {
- highlightById(options.edit.protyle, options.id, "center");
+ if (preview?.currentElement) {
+ scrollCenter(options.edit.protyle, preview.currentElement, "center");
+ } else {
+ highlightById(options.edit.protyle, options.id, "center");
+ }
} else {
scrollToCurrent(options.edit.protyle.contentElement, currentRange, contentRect);
}
@@ -1351,6 +1387,11 @@ export const getArticle = (options: {
setTimeout(() => {
observer.disconnect();
}, Constants.TIMEOUT_COUNT);
+ }, {
+ rootElement: preview?.rootElement,
+ currentElement: preview?.currentElement,
+ excludeSelector: ".av__views [data-type=\"av-search\"], .av__selection-toolbar, .av__calendar-toolbar, .av__row--footer",
+ isValid: isCurrent,
});
} else {
const matchElements = options.edit.protyle.wysiwyg.element.querySelectorAll('span[data-type~="search-mark"]');
diff --git a/app/tests/searchAVPreview.test.js b/app/tests/searchAVPreview.test.js
new file mode 100644
index 0000000000..2a1a3789be
--- /dev/null
+++ b/app/tests/searchAVPreview.test.js
@@ -0,0 +1,214 @@
+const assert = require("node:assert/strict");
+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");
+const path = require("node:path");
+const os = require("node:os");
+
+const sources = () => {
+ const ts = require("typescript");
+ return Object.fromEntries(["search/util", "search/avPreview", "protyle/util/onGet", "protyle/render/searchMarkRender"]
+ .map(name => [name, ts.transpileModule(readFileSync(path.join(__dirname, "../src", name + ".ts"), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},
+ }).outputText]));
+};
+
+const runCases = async modules => {
+ const assert = require("node:assert/strict");
+ const tick = () => new Promise(resolve => setTimeout(resolve, 20));
+ const noop = () => {};
+ const constants = new Proxy({}, {get: (_target, key) => key.startsWith("TIMEOUT") ? 0 : key});
+ window.siyuan = {config: {editor: {dynamicLoadBlocks: 64}}, languages: {}};
+ const initialRenders = [];
+ const targetRenders = [];
+ const targets = [];
+ const requests = new WeakMap();
+ let scrollAnchor;
+ let keyword = "needle";
+ let shape = "av__row";
+ let status = "visible";
+ let absentField = false;
+ const stubs = {
+ constants: {Constants: constants},
+ "util/fetch": {
+ fetchPost(url, data, cb) {
+ if (url === "/api/block/getDocInfo") {
+ cb({code: 0, data: {ial: {}}});
+ } else if (url === "/api/filetree/getDoc") {
+ cb({code: 0, data: {id: "database", mode: 3, rootID: "document", keywords: [keyword],
+ content: '<div class="av" data-type="NodeAttributeView" data-node-id="database"><div></div></div>'}});
+ } else {
+ assert.fail(`Unexpected request: ${url}`);
+ }
+ },
+ async fetchSyncPost(url) {
+ assert.equal(url, "/api/av/getAttributeViewSearchTarget");
+ targets.push(keyword);
+ return {code: 0, data: {itemID: "last-page-row", matchedKeyID: "notes", viewID: "other-view"}};
+ },
+ },
+ "util/pathName": {isEncryptedBox: () => false},
+ "util/noRelyPCFunction": {checkFold: (_id, cb) => cb(false)},
+ "util/highlightById": {highlightById: () => assert.fail("A visible matched item must not highlight the database block"),
+ scrollCenter: (_protyle, element) => { scrollAnchor = element; }},
+ "protyle/util/hasClosest": {hasClosestByClassName: (node, name) =>
+ (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement)?.closest("." + name), hasClosestByTag: () => null,
+ hasClosestByAttribute: () => null, isInEmbedBlock: () => false},
+ "protyle/render/listMindmap/render": {resolveVisibleListMindmapBlock: () => undefined},
+ "protyle/render/av/locate": {setAVLocateRequest: (block, request) => requests.set(block, request)},
+ "protyle/render/av/render": {
+ avRender(element, protyle, cb) {
+ const block = element.matches(".av") ? element : element.querySelector(".av");
+ if (!cb) {
+ return new Promise(resolve => initialRenders.push(resolve));
+ }
+ const request = requests.get(block);
+ assert.equal(request.itemID, "last-page-row");
+ assert.equal(request.keyID, "notes");
+ assert.equal(request.select, false);
+ assert.equal(request.persistView, false);
+ assert.equal(request.viewID, undefined);
+ return new Promise(resolve => targetRenders.push(() => {
+ block.innerHTML = '<div class="av__views"><div data-type="av-search">needle toolbar</div></div>' +
+ (status === "visible" ? `<div class="${shape}" data-id="last-page-row">
+ <div data-dtype="block">Row title</div>
+ <div data-col-id="${absentField ? "hidden-other" : "notes"}" data-field-id="${absentField ? "hidden-other" : "notes"}">${absentField ? "no match" : keyword}</div></div>` : "");
+ cb({target: {status}});
+ resolve();
+ }));
+ },
+ },
+ };
+ const cache = {};
+ const load = name => {
+ if (stubs[name]) {
+ return stubs[name];
+ }
+ if (!modules[name]) {
+ return new Proxy({}, {get: () => noop});
+ }
+ if (!cache[name]) {
+ cache[name] = {};
+ new Function("require", "exports", modules[name] + (name === "search/util" ? "\nexports.renderNextSearchMark = renderNextSearchMark;" : ""))(
+ dependency => load(require("node:path").posix.normalize(require("node:path").posix.dirname(name) + "/" + dependency)),
+ cache[name]);
+ }
+ return cache[name];
+ };
+ const {getArticle, renderNextSearchMark} = load("search/util");
+ const highlighter = load("protyle/render/searchMarkRender");
+ const host = document.createElement("div");
+ host.style.cssText = "height:200px;overflow:auto";
+ const editor = document.createElement("div");
+ editor.className = "protyle-wysiwyg";
+ host.appendChild(editor);
+ document.body.appendChild(host);
+ const protyle = {element: host, contentElement: host, disabled: false, block: {},
+ options: {render: {}}, scroll: {invalidateDynamicLoad: noop},
+ wysiwyg: {element: editor, prepareBlockVirtualization: noop},
+ highlight: {mark: new Highlight(), markHL: new Highlight(), ranges: [],
+ styleElement: Object.assign(document.createElement("style"), {textContent: ""})}};
+ protyle.highlight.styleElement.dataset.uuid = "test-search-preview";
+ const search = () => getArticle({id: "database", edit: {protyle}, config: {method: 0}, value: keyword});
+ for (shape of ["av__row", "av__gallery-item", "av__calendar-item"]) {
+ search();
+ assert.equal(initialRenders.length, 1);
+ const before = targets.length;
+ await tick();
+ assert.equal(targets.length, before, "target lookup waits for initial database rendering");
+ initialRenders.shift()();
+ await tick();
+ assert.equal(targetRenders.length, 1);
+ assert.equal(protyle.highlight.markHL.size, shape === "av__row" ? 0 : 1);
+ targetRenders.shift()();
+ await tick();
+ assert.equal(protyle.highlight.markHL.size, 1);
+ const range = [...protyle.highlight.markHL][0];
+ assert.equal(range.toString(), "needle");
+ assert.ok(range.startContainer.parentElement.closest('[data-id="last-page-row"]'));
+ assert.equal(protyle.highlight.ranges.length, 1, "toolbar text does not become a keyword match");
+ }
+ for (status of ["filtered", "groupHidden"]) {
+ search();
+ initialRenders.shift()();
+ await tick();
+ targetRenders.shift()();
+ await tick();
+ assert.equal(protyle.highlight.markHL.size, 0);
+ assert.equal(protyle.highlight.ranges.length, 0);
+ }
+ status = "visible";
+ absentField = true;
+ search();
+ initialRenders.shift()();
+ await tick();
+ targetRenders.shift()();
+ await tick();
+ assert.equal(protyle.highlight.markHL.size, 1);
+ assert.equal([...protyle.highlight.markHL][0].startContainer, editor.querySelector('[data-id="last-page-row"]'),
+ "hidden fields retain the row as the scroll anchor without exposing their values");
+ assert.equal(scrollAnchor, editor.querySelector('[data-id="last-page-row"]'));
+ scrollAnchor = undefined;
+ renderNextSearchMark({id: "database", edit: {protyle}});
+ assert.equal(scrollAnchor, editor.querySelector('[data-id="last-page-row"]'),
+ "cycling a match in a hidden field keeps the row as the scroll anchor");
+
+ const before = targets.length;
+ search();
+ const oldRender = initialRenders.shift();
+ search();
+ oldRender();
+ await tick();
+ assert.equal(targets.length, before, "an old render of the same database cannot start a new lookup");
+ initialRenders.shift()();
+ await tick();
+ targetRenders.shift()();
+ await tick();
+
+ let valid = true;
+ let completed = false;
+ highlighter.searchMarkRender(protyle, ["no match"], "database", () => { completed = true; }, {isValid: () => valid});
+ valid = false;
+ await tick();
+ assert.equal(completed, false, "a queued keyword scan cannot overwrite a newer preview");
+ host.remove();
+ return "Database search preview cases passed";
+};
+
+if (process.versions.electron && process.type === "browser") {
+ const {app, BrowserWindow} = require("electron");
+ app.setPath("userData", process.argv[2]);
+ app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});
+ try {
+ await win.loadURL("about:blank");
+ console.log(await win.webContents.executeJavaScript(`(${runCases.toString()})(${JSON.stringify(sources())})`));
+ win.destroy();
+ app.exit(0);
+ } catch (error) {
+ console.error(error);
+ win.destroy();
+ app.exit(1);
+ }
+ });
+} else {
+ const {test} = require("node:test");
+ const {execFile} = require("node:child_process");
+ const {promisify} = require("node:util");
+ test("database search preview waits for rendering, locates fields and rejects stale searches", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+ }, async () => {
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-search-av-preview-"));
+ try {
+ const {stdout} = await promisify(execFile)(require("electron"), [__filename, profile], {
+ env, windowsHide: true, timeout: 40000,
+ });
+ assert.match(stdout, /Database search preview cases passed/);
+ } finally {
+ assert.equal(path.dirname(profile), os.tmpdir());
+ assert.ok(path.basename(profile).startsWith("siyuan-search-av-preview-"));
+ rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
+ }
+ });
+}