An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Improve database search results and calendar input https://github.com/siyuan-note/siyuan/issues/20019
Daniel1a10a50fa602
diff --git a/app/src/assets/scss/business/_search.scss b/app/src/assets/scss/business/_search.scssindex 4094fddabd..fdf4a5419f 100644--- a/app/src/assets/scss/business/_search.scss+++ b/app/src/assets/scss/business/_search.scss@@ -2,6 +2,11 @@@use "../component/form";.search {+ &__av-content {+ -webkit-line-clamp: 7;+ overflow-wrap: anywhere;+ }+&__layout {display: flex;flex: 1;diff --git a/app/src/mobile/menu/search.ts b/app/src/mobile/menu/search.tsindex ffa4f55cd4..58ff398be8 100644--- a/app/src/mobile/menu/search.ts+++ b/app/src/mobile/menu/search.ts@@ -204,7 +204,7 @@ ${getFileTreeIconHTML(getNotebookIcon(item.box), "notebook", "b3-list-item__grapresultHTML += `<div style="padding-left: 36px" data-type="search-item" class="b3-list-item" data-node-id="${childItem.id}"><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.content}</span>+<span class="b3-list-item__text${childItem.type === "NodeAttributeView" ? " search__av-content" : ""}">${childItem.content}</span>${getAttr(childItem)}${childItem.tag ? `<span class="b3-list-item__meta b3-list-item__meta--ellipsis">${childItem.tag.replace(/#/g, "")}</span>` : ""}</div>`;@@ -223,7 +223,7 @@ ${childItem.tag ? `<span class="b3-list-item__meta b3-list-item__meta--ellipsis"<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)}- <span class="b3-list-item__text">${item.content}</span>+ <span class="b3-list-item__text${item.type === "NodeAttributeView" ? " search__av-content" : ""}">${item.content}</span>${getAttr(item)}</div><div class="fn__flex">diff --git a/app/src/protyle/render/av/calendar/render.test.ts b/app/src/protyle/render/av/calendar/render.test.tsindex 652e83497f..b631cae819 100644--- a/app/src/protyle/render/av/calendar/render.test.ts+++ b/app/src/protyle/render/av/calendar/render.test.ts@@ -8,6 +8,81 @@ import * as dates from "./date";import {cellValueIsEmpty, createEmptyAVValue} from "../cellValue";import {getConditionalBackground} from "../conditionalColor";+const search = {bindAvSearch() {}, captureAvSearchSelection() {}, deferAvSearchRender: () => false};++test("calendar refreshes the current view after composition and captures the latest selection before replacing the header", async () => {+ const range = {start: new Date(2026, 8, 1).getTime(), end: new Date(2026, 8, 8).getTime(), timeZone: "UTC"};+ const input = {textContent: "before after"};+ const selection = {anchor: 9, focus: 2};+ const root = {querySelectorAll: (): unknown[] => [], querySelector: () => ({addEventListener() {}}),+ addEventListener() {}};+ let composing = true;+ let captured = false;+ let replaced = false;+ let completed = false;+ let refreshed = 0;+ let viewID = "calendar";+ let deferred: () => void;+ let bound: Parameters<typeof import("../search").bindAvSearch>[0];+ const block = {dataset: {}, removeAttribute() {}, querySelector: (selector: string) =>+ selector === ".av__calendar" ? root : input};+ const modules: Record<string, unknown> = {+ "./date": dates,+ "./state": {getCalendarState: () => ({anchor: range.start, mode: "month", rowLimit: 3}), getCalendarRequestRange: () => range},+ "../render": {+ genTabHeaderHTML: (data: IAV) => { assert.equal(data.viewID, viewID); return ""; },+ avRender(element: HTMLElement, protyle: IProtyle, callback: (data: IAV) => void) {+ refreshed++;+ return api.renderCalendar(element, protyle, {viewID,+ view: {calendar: {}, columns: [], rows: [], calendarRange: range}} as unknown as IAV, callback);+ },+ },+ "../../../../util/escape": {escapeAttr: String, escapeHtml: String},+ "../../../../constants": {Constants: {ZWSP: ""}},+ "../container": {replaceAVContainer() { assert.equal(captured, true); replaced = true; }},+ "../virtualScroll": {getAVSelectedItemIDs: (): string[] => [], setAVData() {}},+ "../richText": {renderAVRichTextElements() {}},+ "../locate": {finishAVLocate() {}},+ "../search": {+ deferAvSearchRender(element: unknown, render: () => void) {+ assert.equal(element, input);+ deferred = render;+ return composing;+ },+ captureAvSearchSelection(element: unknown) {+ assert.equal(replaced, false);+ assert.equal(element, input);+ captured = true;+ return selection;+ },+ bindAvSearch(options: typeof bound) { bound = options; },+ },+ };+ const api = {} as typeof import("./render");+ runInNewContext(transpileModule(readFileSync(join(__dirname, "render.ts"), "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},+ }).outputText, {+ exports: api, require: (name: string) => modules[name] || {},+ window: {siyuan: {config: {lang: "en"}, languages: {}}}, document: {activeElement: input},+ });+ await api.renderCalendar(block as unknown as HTMLElement, {disabled: true, options: {}} as IProtyle,+ {viewID: "calendar", view: {calendar: {}, columns: [], rows: [], calendarRange: range}} as unknown as IAV,+ () => { completed = true; });+ assert.equal(replaced, false);+ assert.equal(captured, false);+ assert.equal(completed, false);+ composing = false;+ viewID = "another-calendar";+ input.textContent = "before latest after";+ deferred();+ assert.equal(refreshed, 1);+ assert.equal(replaced, true);+ assert.equal(completed, true);+ assert.equal(bound.query, input.textContent);+ assert.equal(bound.isSearching, true);+ assert.equal(bound.selection, selection);+});+test("calendar omits empty fields while preserving zero, unchecked boxes and rendered values", async () => {const start = new Date(2026, 8, 1).getTime();const range = {start, end: dates.addCalendarDays(start, 7), timeZone: "UTC"};@@ -32,6 +107,7 @@ test("calendar omits empty fields while preserving zero, unchecked boxes and ren"../conditionalColor": {getConditionalBackground},"../cell": {renderCell: () => "<span></span>"},"../render": {genTabHeaderHTML: () => ""},+ "../search": search,"../../../../util/escape": {escapeAttr: String, escapeHtml: String},"../../../../constants": {Constants: {}},"../virtualScroll": {getAVSelectedItemIDs: (): string[] => []},@@ -70,6 +146,7 @@ test("calendar without a date field renders its setup instead of reading an abse"./state": {getCalendarState: () => state, getCalendarRequestRange: () => range},"./settings": {getCalendarSettingsHTML: () => "date-field-settings"},"../render": {genTabHeaderHTML: () => "view-switcher"},+ "../search": search,"../col": {getColNameByType: (type: string) => type},"../../../../util/escape": {escapeAttr: String, escapeHtml: String},"../../../../constants": {Constants: {ZWSP: ""}},@@ -127,7 +204,7 @@ test("calendar refresh keeps selected event segments and blank clicks dismiss th"../../../../constants": {Constants: {ZWSP: ""}},"../container": {replaceAVContainer() {}},"../virtualScroll": {getAVSelectedItemIDs: () => ["selected", "deleted"], setAVData() {}},- "../search": {bindAvSearch() {}},+ "../search": search,"../richText": {renderAVRichTextElements() {}},"../locate": {finishAVLocate() {}},};@@ -204,7 +281,7 @@ test("calendar checkbox clicks and keyboard activation update only the chosen fi"../../../../constants": {Constants: {ZWSP: ""}},"../container": {replaceAVContainer: (_block: unknown, value: string) => { html = value; }},"../virtualScroll": {getAVSelectedItemIDs: (): string[] => [], setAVData() {}},- "../search": {bindAvSearch() {}},+ "../search": search,"../richText": {renderAVRichTextElements() {}},"../locate": {finishAVLocate() {}},};@@ -310,7 +387,7 @@ test("calendar edit-mode changes refresh controls and stale actions cannot creat"../../../../constants": {Constants: {ZWSP: ""}},"../container": {replaceAVContainer: (_block: unknown, value: string) => { html = value; }},"../virtualScroll": {getAVData: () => data, getAVSelectedItemIDs: (): string[] => [], setAVData() {}},- "../search": {bindAvSearch() {}},+ "../search": search,"../richText": {renderAVRichTextElements() {}},"../locate": {finishAVLocate() {}},"../render/av/calendar/render": calendar,diff --git a/app/src/protyle/render/av/calendar/render.ts b/app/src/protyle/render/av/calendar/render.tsindex 07e9f16452..0e1e0b167e 100644--- a/app/src/protyle/render/av/calendar/render.ts+++ b/app/src/protyle/render/av/calendar/render.ts@@ -16,7 +16,7 @@ import {avRender, genTabHeaderHTML, updateSearch} from "../render";import {replaceAVContainer} from "../container";import {renderAVRichTextElements} from "../richText";import {avContextmenu} from "../action";-import {bindAvSearch} from "../search";+import {bindAvSearch, captureAvSearchSelection, deferAvSearchRender} from "../search";import {getAVData, getAVSelectedItemIDs, setAVData} from "../virtualScroll";import {addCalendarDays, calendarDay, calendarDayDistance, getCalendarDate, getCalendarInterval, getISOWeekForCalendarRow, ICalendarEvent, ICalendarSegment,isCalendarDateEditable, moveCalendarDate, packCalendarWeek, resizeCalendarDate} from "./date";@@ -349,6 +349,14 @@ const bindCalendarDrag = (root: HTMLElement, protyle: IProtyle, blockElement: HT};export const renderCalendar = async (blockElement: HTMLElement, protyle: IProtyle, data: IAV, cb?: (data: IAV) => void) => {+ const search = blockElement.querySelector<HTMLElement>('[data-type="av-search"]');+ if (deferAvSearchRender(search, () => {+ // 组合输入结束后重新读取当前视图和查询,并沿用渲染请求的过期检查。+ blockElement.removeAttribute("data-render");+ void avRender(blockElement, protyle, cb);+ })) {+ return;+ }const view = data.view as IAVTable;const state = getCalendarState(blockElement, data.viewID);const rowLimit = view.calendar.rowLimit || 3;@@ -374,9 +382,9 @@ export const renderCalendar = async (blockElement: HTMLElement, protyle: IProtylreturn;}const editable = canEditCalendar(protyle);- const search = blockElement.querySelector<HTMLElement>('[data-type="av-search"]');const query = search?.textContent || "";const isSearching = search === document.activeElement;+ const selection = captureAvSearchSelection(search);const hasUndated = !!dateColumn && state.undatedCount?.dateKeyID === dateColumn.id && state.undatedCount.query === query.trim() &&state.undatedCount.total > 0;const events: ICalendarEvent[] = [];@@ -593,7 +601,7 @@ export const renderCalendar = async (blockElement: HTMLElement, protyle: IProtylif (!dateColumn && editable) {bindCalendarSettings({protyle, blockElement, data, menuElement: root});}- bindAvSearch({blockElement, query, isSearching, onChange: () => updateSearch(blockElement, protyle)});+ bindAvSearch({blockElement, query, isSearching, selection, onChange: () => updateSearch(blockElement, protyle)});renderAVRichTextElements(blockElement);finishAVLocate(blockElement, protyle, data);cb?.(data);diff --git a/app/src/protyle/render/av/search.dom.test.ts b/app/src/protyle/render/av/search.dom.test.tsnew file mode 100644index 0000000000..84c6d02067--- /dev/null+++ b/app/src/protyle/render/av/search.dom.test.ts@@ -0,0 +1,130 @@+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 {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const browserCases = async (source: string) => {+ const check: typeof assert = require("node:assert/strict");+ const api = {} as typeof import("./search");+ new Function("exports", "require", source)(api, () => ({addClearButton() {}, electronUndo() {}}));+ const block = document.createElement("div");+ document.body.append(block);+ const header = '<div class="av__views"><div data-type="av-search" contenteditable="plaintext-only"></div></div>';+ block.innerHTML = header;+ const input = () => block.querySelector<HTMLElement>('[data-type="av-search"]');+ const bind = (query: string, isSearching = true, selection?: ReturnType<typeof api.captureAvSearchSelection>) => {+ api.bindAvSearch({blockElement: block, query, isSearching, selection, onChange() {}});+ };+ const render = () => {+ const query = input().textContent;+ const isSearching = document.activeElement === input();+ const selection = api.captureAvSearchSelection(input());+ block.innerHTML = header;+ bind(query, isSearching, selection);+ };+ const select = (anchor: number, focus = anchor) => {+ const node = input().firstChild || input();+ getSelection().setBaseAndExtent(node, anchor, node, focus);+ };+ const checkSelection = (anchor: number, focus = anchor) => {+ check.equal(document.activeElement, input());+ check.equal(getSelection().anchorNode, input().firstChild || input());+ check.equal(getSelection().focusNode, input().firstChild || input());+ check.equal(getSelection().anchorOffset, anchor);+ check.equal(getSelection().focusOffset, focus);+ };+ for (const [anchor, focus] of [[0, 0], [7, 7], [12, 12], [2, 9], [9, 2]]) {+ bind("before after");+ select(anchor, focus);+ render();+ checkSelection(anchor, focus);+ }+ select(7);+ check.equal(document.execCommand("insertText", false, "X"), true);+ render();+ check.equal(input().textContent, "before Xafter");+ checkSelection(8);+ select(8, 7);+ check.equal(document.execCommand("delete"), true);+ render();+ check.equal(input().textContent, "before after");+ checkSelection(7);++ bind("");+ select(0);+ render();+ checkSelection(0);+ bind("前😀后");+ input().replaceChildren(document.createTextNode("前😀"), document.createTextNode("后"));+ getSelection().setBaseAndExtent(input().lastChild, 1, input().firstChild, 1);+ render();+ checkSelection(4, 1);++ bind("前后");+ const original = input();+ select(1);+ original.dispatchEvent(new CompositionEvent("compositionstart", {bubbles: true}));+ check.equal(api.deferAvSearchRender(original, render), true);+ original.textContent = "前你好后";+ original.dispatchEvent(new InputEvent("input", {bubbles: true, isComposing: true, inputType: "insertCompositionText"}));+ check.equal(input(), original);+ original.dispatchEvent(new CompositionEvent("compositionend", {bubbles: true, data: "你好"}));+ select(3);+ original.dispatchEvent(new InputEvent("input", {bubbles: true, inputType: "insertText"}));+ await new Promise(resolve => setTimeout(resolve, 0));+ check.notEqual(input(), original);+ check.equal(input().textContent, "前你好后");+ checkSelection(3);++ const outside = document.createElement("input");+ document.body.append(outside);+ outside.focus();+ render();+ check.equal(document.activeElement, outside);+ block.remove();+ outside.remove();+ return "Database search DOM cases passed";+};++test("database search preserves real DOM selection, edits and composition across replacement", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 45000,+}, async () => {+ const source = transpileModule(readFileSync(path.join(__dirname, "search.ts"), "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},+ }).outputText;+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-av-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}});+ 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 {stdout} = await promisify(execFile)(require("electron") as unknown as string, [script],+ {env, timeout: 40000, windowsHide: true});+ assert.match(stdout, /Database search DOM cases passed/);+ } finally {+ assert.equal(path.dirname(path.resolve(temporary)), path.resolve(tmpdir()));+ assert.ok(path.basename(temporary).startsWith("siyuan-av-search-test-"));+ rmSync(temporary, {recursive: true, force: true});+ }+});diff --git a/app/src/protyle/render/av/search.test.ts b/app/src/protyle/render/av/search.test.tsnew file mode 100644index 0000000000..cf96821034--- /dev/null+++ b/app/src/protyle/render/av/search.test.ts@@ -0,0 +1,165 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {join} from "node:path";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const setup = (text = "before after") => {+ type TText = {textContent: string};+ const restored: unknown[][] = [];+ const selection = {+ rangeCount: 1,+ anchorNode: null as unknown,+ anchorOffset: 0,+ focusNode: null as unknown,+ focusOffset: 0,+ setBaseAndExtent(...args: unknown[]) { restored.push(args); },+ };+ const document = {+ activeElement: null as unknown,+ createRange: () => {+ let input: ReturnType<typeof createInput>;+ let end: unknown;+ let offset = 0;+ return {+ selectNodeContents(element: typeof input) { input = element; },+ setEnd(node: unknown, position: number) { end = node; offset = position; },+ toString: () => end === input ? input.childNodes.slice(0, offset).map(node => node.textContent).join("") :+ input.childNodes.slice(0, input.childNodes.indexOf(end as TText)).map(node => node.textContent).join("") ++ (end as TText).textContent.slice(0, offset),+ };+ },+ };+ const createInput = () => {+ const handlers: Record<string, (event: unknown) => void> = {};+ return {+ handlers,+ childNodes: [] as TText[],+ isConnected: true,+ style: {},+ get textContent(): string { return this.childNodes.map((node: TText) => node.textContent).join(""); },+ set textContent(value: string) { this.childNodes = value ? [{textContent: value}] : []; },+ get firstChild() { return this.childNodes[0] || null; },+ contains(node: unknown): boolean { return node === this || this.childNodes.includes(node as TText); },+ focus() { document.activeElement = this; },+ addEventListener(type: string, handler: (event: unknown) => void) { handlers[type] = handler; },+ };+ };+ let input = createInput();+ let changed = 0;+ const timers: (() => void)[] = [];+ const modules: Record<string, unknown> = {+ "../../../util/addClearButton": {addClearButton() {}},+ "../../util/selection": {focusBlock() {}},+ "../../undo": {electronUndo() {}},+ };+ const api = {} as typeof import("./search");+ runInNewContext(transpileModule(readFileSync(join(__dirname, "search.ts"), "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},+ }).outputText, {+ exports: api, require: (name: string) => modules[name] || {}, document,+ getSelection: () => selection, setTimeout: (callback: () => void) => timers.push(callback),+ });+ const blockElement = {querySelector: (selector: string) => selector === ".av__views" ?+ {classList: {add() {}, remove() {}}} : input} as unknown as HTMLElement;+ const bind = (query: string, isSearching = true, saved?: ReturnType<typeof api.captureAvSearchSelection>) => {+ api.bindAvSearch({blockElement, query, isSearching, selection: saved, onChange: () => changed++});+ };+ const replace = () => {+ const query = input.textContent;+ const isSearching = document.activeElement === input;+ const saved = api.captureAvSearchSelection(input as unknown as HTMLElement);+ input.isConnected = false;+ input = createInput();+ bind(query, isSearching, saved);+ };+ bind(text);+ const select = (anchor: unknown, anchorOffset: number, focus = anchor, focusOffset = anchorOffset) => {+ Object.assign(selection, {anchorNode: anchor, anchorOffset, focusNode: focus, focusOffset});+ };+ const dispatch = (name: string, isComposing = false) => input.handlers[name]({isComposing, stopPropagation() {}});+ return {api, bind, replace, select, dispatch, restored, document, selection, timers,+ input: () => input, changed: () => changed};+};++test("database search restores beginning, middle, end and directional selections after replacement", () => {+ for (const [anchor, focus] of [[0, 0], [7, 7], [12, 12], [2, 9], [9, 2]]) {+ const f = setup();+ f.select(f.input().firstChild, anchor, f.input().firstChild, focus);+ f.replace();+ assert.deepEqual(f.restored, [[f.input().firstChild, anchor, f.input().firstChild, focus]]);+ assert.equal(f.document.activeElement, f.input());+ assert.equal(f.input().textContent, "before after");+ }+});++test("database search captures split text, Unicode, element boundaries and an empty query", () => {+ const f = setup();+ f.input().childNodes = [{textContent: "前😀"}, {textContent: "选中后"}];+ f.select(f.input().childNodes[1], 2, f.input().childNodes[0], 1);+ f.replace();+ assert.deepEqual(f.restored.pop(), [f.input().firstChild, 5, f.input().firstChild, 1]);+ f.input().childNodes = [{textContent: "前😀"}, {textContent: "后"}];+ f.select(f.input(), 1);+ f.replace();+ assert.deepEqual(f.restored.pop(), [f.input().firstChild, 3, f.input().firstChild, 3]);+ f.input().textContent = "";+ f.select(f.input(), 0);+ f.replace();+ assert.deepEqual(f.restored.pop(), [f.input(), 0, f.input(), 0]);+});++test("database search does not capture an outside selection or restore focus after blur", () => {+ const f = setup();+ f.select(f.input().firstChild, 2, {}, 0);+ assert.equal(f.api.captureAvSearchSelection(f.input() as unknown as HTMLElement), undefined);+ f.select(f.input().firstChild, 2);+ f.selection.rangeCount = 0;+ assert.equal(f.api.captureAvSearchSelection(f.input() as unknown as HTMLElement), undefined);+ f.selection.rangeCount = 1;+ const outside = {};+ f.document.activeElement = outside;+ f.replace();+ assert.equal(f.document.activeElement, outside);+ assert.deepEqual(f.restored, []);+});++test("database search defers the latest render until composition and its final input finish", () => {+ const f = setup("前后");+ const original = f.input();+ let rendered = "";+ f.dispatch("compositionstart");+ for (const composing of [true, false]) {+ f.dispatch("input", composing);+ }+ assert.equal(f.changed(), 0);+ assert.equal(f.api.deferAvSearchRender(original as unknown as HTMLElement, () => { rendered = "old"; }), true);+ assert.equal(f.api.deferAvSearchRender(original as unknown as HTMLElement, () => {+ rendered = "latest";+ f.replace();+ }), true);+ original.textContent = "前你好后";+ f.dispatch("compositionend");+ assert.equal(f.changed(), 1);+ assert.equal(rendered, "");+ assert.equal(f.input(), original);+ f.select(original.firstChild, 3);+ f.dispatch("input");+ f.timers.shift()();+ assert.equal(rendered, "latest");+ assert.equal(f.input().textContent, "前你好后");+ assert.deepEqual(f.restored, [[f.input().firstChild, 3, f.input().firstChild, 3]]);+ assert.equal(f.api.deferAvSearchRender(f.input() as unknown as HTMLElement, () => {}), false);+});++test("database search cancels a deferred render when its input has already been replaced or removed", () => {+ const f = setup();+ let rendered = false;+ f.dispatch("compositionstart");+ f.api.deferAvSearchRender(f.input() as unknown as HTMLElement, () => { rendered = true; });+ f.dispatch("compositionend");+ f.input().isConnected = false;+ f.timers.shift()();+ assert.equal(rendered, false);+});diff --git a/app/src/protyle/render/av/search.ts b/app/src/protyle/render/av/search.tsindex 5fc55c31d4..c4861331ae 100644--- a/app/src/protyle/render/av/search.ts+++ b/app/src/protyle/render/av/search.ts@@ -5,6 +5,38 @@ import {electronUndo} from "../../undo";import {activeBlur} from "../../../mobile/util/keyboardToolbar";/// #endif+const composingSearches = new WeakMap<HTMLElement, {render?: () => void}>();++export const deferAvSearchRender = (searchInputElement: HTMLElement, render: () => void) => {+ const composition = composingSearches.get(searchInputElement);+ if (!composition) {+ return false;+ }+ composition.render = render;+ return true;+};++export const captureAvSearchSelection = (searchInputElement: HTMLElement) => {+ if (!searchInputElement || document.activeElement !== searchInputElement) {+ return;+ }+ const selection = getSelection();+ if (!selection?.rangeCount || !searchInputElement.contains(selection.anchorNode) ||+ !searchInputElement.contains(selection.focusNode)) {+ return;+ }+ const offset = (node: Node, position: number) => {+ const range = document.createRange();+ range.selectNodeContents(searchInputElement);+ range.setEnd(node, position);+ return range.toString().length;+ };+ return {+ anchor: offset(selection.anchorNode, selection.anchorOffset),+ focus: offset(selection.focusNode, selection.focusOffset),+ };+};+const collapseAvSearch = (searchInputElement: HTMLElement, viewsElement: HTMLElement) => {viewsElement.classList.remove("av__views--show", "av__views--search");searchInputElement.style.width = "0";@@ -16,6 +48,7 @@ export const bindAvSearch = (options: {blockElement: HTMLElement,query?: string,isSearching?: boolean,+ selection?: ReturnType<typeof captureAvSearchSelection>,onChange: () => void,}) => {const viewsElement = options.blockElement.querySelector(".av__views") as HTMLElement;@@ -23,9 +56,16 @@ export const bindAvSearch = (options: {searchInputElement.textContent = options.query || "";if (options.isSearching) {searchInputElement.focus();+ if (options.selection) {+ const node = searchInputElement.firstChild || searchInputElement;+ const length = searchInputElement.textContent.length;+ getSelection().setBaseAndExtent(node, Math.min(options.selection.anchor, length),+ node, Math.min(options.selection.focus, length));+ }}searchInputElement.addEventListener("compositionstart", (event: KeyboardEvent) => {event.stopPropagation();+ composingSearches.set(searchInputElement, {});});searchInputElement.addEventListener("keydown", (event: KeyboardEvent) => {if (event.isComposing) {@@ -40,7 +80,7 @@ export const bindAvSearch = (options: {});const searchInputChange = (event: Event) => {event.stopPropagation();- if ((event as KeyboardEvent).isComposing) {+ if ((event as KeyboardEvent).isComposing || composingSearches.has(searchInputElement)) {return;}if (searchInputElement.textContent || document.activeElement === searchInputElement) {@@ -58,7 +98,17 @@ export const bindAvSearch = (options: {});});searchInputElement.addEventListener("compositionend", () => {+ const render = composingSearches.get(searchInputElement)?.render;+ composingSearches.delete(searchInputElement);options.onChange();+ if (render) {+ // 等待组合输入的最终 input 和选区更新后,再重建搜索框。+ setTimeout(() => {+ if (searchInputElement.isConnected) {+ render();+ }+ });+ }});searchInputElement.addEventListener("blur", (event: KeyboardEvent) => {if (event.isComposing) {diff --git a/app/src/search/util.ts b/app/src/search/util.tsindex c460c18d7d..ed23d95cd6 100644--- a/app/src/search/util.ts+++ b/app/src/search/util.ts@@ -1600,7 +1600,7 @@ ${getFileTreeIconHTML(getNotebookIcon(item.box), "notebook", "b3-list-item__grapresultHTML += `<div style="padding-left: 36px" data-type="search-item" class="b3-list-item" data-node-id="${childItem.id}" data-root-id="${childItem.rootID}" data-node-type="${childItem.type || ""}"><svg class="b3-list-item__graphic popover__block" data-id="${childItem.id}"><use xlink:href="#${getIconByType(childItem.type)}"></use></svg>${unicode2Emoji(childItem.ial.icon, "b3-list-item__graphic", true)}-<span class="b3-list-item__text">${childItem.content}</span>+<span class="b3-list-item__text${childItem.type === "NodeAttributeView" ? " search__av-content" : ""}">${childItem.content}</span>${getAttr(childItem)}${childItem.tag ? `<span class="b3-list-item__meta b3-list-item__meta--ellipsis">${childItem.tag.replace(/#/g, "")}</span>` : ""}${countHTML}@@ -1622,7 +1622,7 @@ ${countHTML}resultHTML += `<div data-type="search-item" class="b3-list-item" data-node-id="${item.id}" data-root-id="${item.rootID}" data-node-type="${item.type || ""}"><svg class="b3-list-item__graphic popover__block" data-id="${item.id}"><use xlink:href="#${getIconByType(item.type)}"></use></svg>${unicode2Emoji(item.ial.icon, "b3-list-item__graphic", true)}-<span class="b3-list-item__text">${item.content}</span>+<span class="b3-list-item__text${item.type === "NodeAttributeView" ? " search__av-content" : ""}">${item.content}</span>${getAttr(item)}${item.tag ? `<span class="b3-list-item__meta b3-list-item__meta--ellipsis">${item.tag.replace(/#/g, "")}</span>` : ""}<span class="b3-list-item__meta b3-list-item__meta--ellipsis ariaLabel" aria-label="${escapeAriaLabel(escapeHtml(title))}">${title}</span>diff --git a/kernel/model/search.go b/kernel/model/search.goindex c4a1b9ab27..4e68fd9838 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -1699,6 +1699,9 @@ func FullTextSearchBlockInBoxWithHPathContext(ctx context.Context, query string,}}pageCount = (matchedBlockCount + pageSize - 1) / pageSize+ if 2 != method {+ compactAttributeViewSearchResults(blocks)+ }switch groupBy {case 0: // 不分组diff --git a/kernel/model/search_attribute_view.go b/kernel/model/search_attribute_view.gonew file mode 100644index 0000000000..30f40155f0--- /dev/null+++ b/kernel/model/search_attribute_view.go@@ -0,0 +1,254 @@+package model++import (+ "html"+ "strings"+ "unicode/utf8"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++type attributeViewSearchRange struct {+ start, end int+}++type attributeViewSearchPart struct {+ text string+ start int+ key *av.Key+ value *av.Value+ view bool+ ranges []attributeViewSearchRange+}++// compactAttributeViewSearchResults 只精简已命中的数据库块,不改变索引、结果数量和排序。+func compactAttributeViewSearchResults(blocks []*Block) {+ for _, block := range blocks {+ if "NodeAttributeView" != block.Type || !strings.Contains(block.Content, "<mark>") {+ continue+ }+ tree, err := LoadTreeByBlockIDInExactBox(block.ID, block.Box)+ if nil != err || nil == tree {+ continue+ }+ node := treenode.GetNodeInTree(tree, block.ID)+ if nil == node || ast.NodeAttributeView != node.Type || "" == node.AttributeViewID {+ continue+ }+ avBox := ""+ if IsEncryptedBox(tree.Box) {+ avBox = tree.Box+ }+ attrView, err := av.ParseAttributeViewForIndexInBox(node.AttributeViewID, avBox)+ if nil != err || nil == attrView {+ continue+ }+ block.Content = compactAttributeViewSearchContent(attrView, block.Content)+ }+}++func compactAttributeViewSearchContent(attrView *av.AttributeView, fallback string) string {+ // 按索引内容的顺序记录字段边界,将现有高亮映射回原文,不重新匹配关键词。+ var source strings.Builder+ var parts []*attributeViewSearchPart+ appendPart := func(text string, key *av.Key, value *av.Value, view bool) {+ parts = append(parts, &attributeViewSearchPart{text: text, start: source.Len(), key: key, value: value, view: view})+ source.WriteString(text)+ source.WriteByte(' ')+ }+ appendPart(attrView.Name, nil, nil, false)+ for _, view := range attrView.Views {+ if nil == view {+ return fallback+ }+ appendPart(view.Name, nil, nil, true)+ }+ for _, keyValues := range attrView.KeyValues {+ if nil == keyValues || nil == keyValues.Key {+ return fallback+ }+ appendPart(keyValues.Key.Name, keyValues.Key, nil, false)+ for _, value := range keyValues.Values {+ if nil != value {+ appendPart(value.String(true), keyValues.Key, value, false)+ }+ }+ }+ ranges, ok := mapAttributeViewSearchRanges(source.String(), fallback)+ if !ok {+ return fallback+ }+ for _, match := range ranges {+ found := false+ for _, part := range parts {+ if part.start <= match.start && match.end <= part.start+len(part.text) {+ if part.view {+ return fallback+ }+ part.ranges = append(part.ranges, attributeViewSearchRange{match.start - part.start, match.end - part.start})+ found = true+ break+ }+ }+ if !found {+ // 跨字段短语、视图名称或过期索引无法精确归属时保留原片段。+ return fallback+ }+ }+ rowTitles := map[string]string{}+ for _, part := range parts {+ if nil != part.value && av.KeyTypeBlock == part.key.Type {+ rowTitles[part.value.BlockID] = part.text+ }+ }+ var lines []string+ if "" != attrView.Name {+ lines = append(lines, attributeViewSearchPartHTML(parts[0]))+ }+ const maxFields = 6+ fields := 0+ for _, part := range parts {+ if nil == part.key || 0 == len(part.ranges) {+ continue+ }+ key := util.EscapeHTML(attributeViewSearchSummary(part.key.Name, 60))+ if nil == part.value {+ key = attributeViewSearchPartHTML(part)+ }+ line := `<span class="fn__code">` + key + `</span>`+ if nil != part.value {+ line += " " + attributeViewSearchPartHTML(part)+ if av.KeyTypeBlock != part.key.Type {+ if rowTitle := rowTitles[part.value.BlockID]; "" != rowTitle {+ line = util.EscapeHTML(attributeViewSearchSummary(rowTitle, 48)) + " · " + line+ }+ }+ }+ lines = append(lines, line)+ fields+++ if fields >= maxFields {+ break+ }+ }+ if 0 == len(lines) {+ return fallback+ }+ return strings.Join(lines, "<br>")+}++// mapAttributeViewSearchRanges 只接受可唯一定位的搜索片段,避免把同词子串误归到其他字段。+func mapAttributeViewSearchRanges(source, marked string) ([]attributeViewSearchRange, bool) {+ plain, ranges, ok := parseAttributeViewSearchMarks(marked)+ if !ok || 0 == len(ranges) {+ return nil, false+ }+ mapWindow := func(window string, matches []attributeViewSearchRange, after int) ([]attributeViewSearchRange, bool) {+ pos := strings.Index(source, window)+ if "" == window || pos < after || strings.LastIndex(source, window) != pos {+ return nil, false+ }+ mapped := make([]attributeViewSearchRange, len(matches))+ for i, match := range matches {+ mapped[i] = attributeViewSearchRange{pos + match.start, pos + match.end}+ }+ return mapped, true+ }+ if mapped, found := mapWindow(plain, ranges, 0); found {+ return mapped, true+ }+ if strings.Contains(source, "...") {+ return nil, false+ }+ var mapped []attributeViewSearchRange+ offset, after := 0, 0+ for _, window := range strings.Split(plain, "...") {+ var matches []attributeViewSearchRange+ for _, match := range ranges {+ if offset <= match.start && match.end <= offset+len(window) {+ matches = append(matches, attributeViewSearchRange{match.start - offset, match.end - offset})+ }+ }+ if 0 < len(matches) {+ resolved, found := mapWindow(window, matches, after)+ if !found {+ return nil, false+ }+ mapped = append(mapped, resolved...)+ after = resolved[len(resolved)-1].end+ }+ offset += len(window) + len("...")+ }+ return mapped, len(mapped) == len(ranges)+}++func parseAttributeViewSearchMarks(marked string) (string, []attributeViewSearchRange, bool) {+ var plain strings.Builder+ var ranges []attributeViewSearchRange+ for {+ start := strings.Index(marked, "<mark>")+ if start < 0 {+ plain.WriteString(html.UnescapeString(marked))+ return plain.String(), ranges, !strings.Contains(marked, "</mark>")+ }+ if strings.Contains(marked[:start], "</mark>") {+ return "", nil, false+ }+ plain.WriteString(html.UnescapeString(marked[:start]))+ marked = marked[start+len("<mark>"):]+ end := strings.Index(marked, "</mark>")+ if end <= 0 || strings.Contains(marked[:end], "<mark>") {+ return "", nil, false+ }+ matchStart := plain.Len()+ plain.WriteString(html.UnescapeString(marked[:end]))+ ranges = append(ranges, attributeViewSearchRange{matchStart, plain.Len()})+ marked = marked[end+len("</mark>"):]+ }+}++func attributeViewSearchSummary(text string, limit int) string {+ runes := []rune(text)+ if len(runes) > limit {+ return string(runes[:limit]) + "..."+ }+ return text+}++func attributeViewSearchPartHTML(part *attributeViewSearchPart) string {+ if 0 == len(part.ranges) {+ return util.EscapeHTML(attributeViewSearchSummary(part.text, 80))+ }+ start, end := part.ranges[0].start, part.ranges[0].end+ for i := 0; i < 32 && start > 0; i++ {+ _, size := utf8.DecodeLastRuneInString(part.text[:start])+ start -= size+ }+ for i := 0; i < 64 && end < len(part.text); i++ {+ _, size := utf8.DecodeRuneInString(part.text[end:])+ end += size+ }+ var result strings.Builder+ if start > 0 {+ result.WriteString("...")+ }+ cursor := start+ for _, match := range part.ranges {+ if match.start >= end {+ break+ }+ if match.end > end {+ end = match.end+ }+ result.WriteString(util.EscapeHTML(part.text[cursor:match.start]))+ result.WriteString("<mark>" + util.EscapeHTML(part.text[match.start:match.end]) + "</mark>")+ cursor = match.end+ }+ result.WriteString(util.EscapeHTML(part.text[cursor:end]))+ if end < len(part.text) {+ result.WriteString("...")+ }+ return result.String()+}diff --git a/kernel/model/search_attribute_view_test.go b/kernel/model/search_attribute_view_test.gonew file mode 100644index 0000000000..00b780dc24--- /dev/null+++ b/kernel/model/search_attribute_view_test.go@@ -0,0 +1,289 @@+package model++import (+ "reflect"+ "strings"+ "testing"+ "unicode/utf8"++ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAttributeViewSearchParseMarks(t *testing.T) {+ tests := []struct {+ name, marked, plain string+ ranges []attributeViewSearchRange+ ok bool+ }{+ {name: "plain", marked: "A&B", plain: "A&B", ok: true},+ {name: "entities and multibyte offsets", marked: "前&<mark>🙂<x></mark>后", plain: "前&🙂<x>后", ranges: []attributeViewSearchRange{{len("前&"), len("前&🙂<x>")}}, ok: true},+ {name: "literal markup", marked: "<mark><mark>safe</mark></mark>", plain: "<mark>safe</mark>", ranges: []attributeViewSearchRange{{6, 10}}, ok: true},+ {name: "adjacent marks", marked: "<mark>a</mark><mark>b</mark>", plain: "ab", ranges: []attributeViewSearchRange{{0, 1}, {1, 2}}, ok: true},+ {name: "unclosed mark", marked: "before <mark>hit"},+ {name: "empty mark", marked: "<mark></mark>"},+ {name: "nested mark", marked: "<mark>a<mark>b</mark></mark>"},+ {name: "stray closing tail", marked: "<mark>a</mark></mark>"},+ {name: "stray closing prefix", marked: "</mark><mark>a</mark>"},+ {name: "stray closing between marks", marked: "<mark>a</mark></mark><mark>b</mark>"},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ plain, ranges, ok := parseAttributeViewSearchMarks(test.marked)+ if ok != test.ok {+ t.Fatalf("valid = %v, want %v; plain = %q, ranges = %#v", ok, test.ok, plain, ranges)+ }+ if ok && (plain != test.plain || !reflect.DeepEqual(ranges, test.ranges)) {+ t.Fatalf("got (%q, %#v), want (%q, %#v)", plain, ranges, test.plain, test.ranges)+ }+ })+ }+}++func TestAttributeViewSearchMapRanges(t *testing.T) {+ tests := []struct {+ name, source, marked string+ matches []string+ ok bool+ }{+ {name: "full indexed text", source: "DB View Field value ", marked: "DB View Field <mark>value</mark>", matches: []string{"value"}, ok: true},+ {name: "trimmed outer whitespace", source: " DB Field value \t ", marked: "DB Field <mark>value</mark>", matches: []string{"value"}, ok: true},+ {name: "unique context resolves repeated word", source: "DB first foo second foo ", marked: "first <mark>foo</mark>", matches: []string{"foo"}, ok: true},+ {name: "ellipsis windows", source: "DB first foo long unused text second bar ", marked: "...first <mark>foo</mark>...second <mark>bar</mark>...", matches: []string{"foo", "bar"}, ok: true},+ {name: "literal ellipsis exact text", source: "DB Field a...b ", marked: "DB Field <mark>a...b</mark>", matches: []string{"a...b"}, ok: true},+ {name: "entities", source: "DB A&B <x> ", marked: "DB A&B <mark><x></mark>", matches: []string{"<x>"}, ok: true},+ {name: "unmarked snippet", source: "DB foo ", marked: "DB foo"},+ {name: "ambiguous word", source: "DB first foo second foo ", marked: "<mark>foo</mark>"},+ {name: "stale snippet", source: "DB new value ", marked: "DB <mark>old</mark> value"},+ {name: "reversed windows", source: "DB first foo second bar ", marked: "...second <mark>bar</mark>...first <mark>foo</mark>..."},+ {name: "mark crosses omitted text", source: "DB foo gap bar ", marked: "...<mark>foo...bar</mark>..."},+ {name: "literal ellipsis prevents guessing", source: "DB a...b Field target ", marked: "...Field <mark>target</mark>..."},+ {name: "truncated generated markup", source: "DB target ", marked: "DB <mark>target"},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ ranges, ok := mapAttributeViewSearchRanges(test.source, test.marked)+ if ok != test.ok {+ t.Fatalf("mapped = %v, want %v; ranges = %#v", ok, test.ok, ranges)+ }+ if !ok {+ return+ }+ if len(ranges) != len(test.matches) {+ t.Fatalf("got %d ranges, want %d", len(ranges), len(test.matches))+ }+ lastEnd := 0+ for i, match := range ranges {+ if match.start < lastEnd || match.end > len(test.source) || match.start >= match.end {+ t.Fatalf("invalid or out-of-order range %#v", match)+ }+ if got := test.source[match.start:match.end]; got != test.matches[i] {+ t.Fatalf("range %d = %q, want %q", i, got, test.matches[i])+ }+ lastEnd = match.end+ }+ })+ }+}++func TestAttributeViewSearchCompactActualMatches(t *testing.T) {+ attrView := attributeViewSearchTestFixture()+ const source = "Contacts All people Title Project Apollo Project Borealis Status cat concatenate"+ tests := []struct {+ name, marked string+ contains []string+ absent []string+ }{+ {+ name: "field name only",+ marked: strings.Replace(source, "Status", "<mark>Status</mark>", 1),+ contains: []string{`<span class="fn__code"><mark>Status</mark></span>`},+ absent: []string{"Project Apollo", "Project Borealis", "concatenate", ">cat<", "All people"},+ },+ {+ name: "FTS term does not expand into another value",+ marked: strings.Replace(source, "cat concatenate", "<mark>cat</mark> concatenate", 1),+ contains: []string{"Project Apollo", `<span class="fn__code">Status</span>`, "<mark>cat</mark>"},+ absent: []string{"Project Borealis", "concatenate", "All people"},+ },+ {+ name: "regex substring retains actual value",+ marked: strings.Replace(source, "concatenate", "con<mark>cat</mark>enate", 1),+ contains: []string{"Project Borealis", "con<mark>cat</mark>enate"},+ absent: []string{"Project Apollo", "All people"},+ },+ {+ name: "primary value needs no duplicate row label",+ marked: strings.Replace(source, "Project Apollo", "Project <mark>Apollo</mark>", 1),+ contains: []string{`<span class="fn__code">Title</span> Project <mark>Apollo</mark>`},+ absent: []string{"Project Apollo ·", "Status", "Project Borealis", "concatenate"},+ },+ {+ name: "two actual value hits",+ marked: strings.Replace(strings.Replace(source, "cat concatenate", "<mark>cat</mark> concatenate", 1), "concatenate", "<mark>concatenate</mark>", 1),+ contains: []string{"Project Apollo", "Project Borealis", "<mark>cat</mark>", "<mark>concatenate</mark>"},+ absent: []string{"All people"},+ },+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ got := compactAttributeViewSearchContent(attrView, test.marked)+ if got == test.marked {+ t.Fatalf("expected compact content, retained fallback %q", got)+ }+ for _, want := range test.contains {+ if !strings.Contains(got, want) {+ t.Errorf("content %q does not contain %q", got, want)+ }+ }+ for _, unwanted := range test.absent {+ if strings.Contains(got, unwanted) {+ t.Errorf("content %q includes unrelated text %q", got, unwanted)+ }+ }+ })+ }+}++func TestAttributeViewSearchCompactFallback(t *testing.T) {+ const source = "Contacts All people Title Project Apollo Project Borealis Status cat concatenate"+ tests := []struct {+ name, marked string+ mutate func(*av.AttributeView)+ }{+ {name: "view only", marked: strings.Replace(source, "All people", "<mark>All people</mark>", 1)},+ {name: "value plus view", marked: strings.Replace(strings.Replace(source, "All people", "<mark>All people</mark>", 1), "cat concatenate", "<mark>cat</mark> concatenate", 1)},+ {name: "cross-field phrase", marked: strings.Replace(source, "Status cat", "<mark>Status cat</mark>", 1)},+ {name: "cross-value phrase", marked: strings.Replace(source, "cat concatenate", "<mark>cat concatenate</mark>", 1)},+ {name: "valid value plus cross-field phrase", marked: strings.Replace(strings.Replace(source, "Project Apollo", "Project <mark>Apollo</mark>", 1), "Status cat", "<mark>Status cat</mark>", 1)},+ {name: "stale AV", marked: strings.Replace(source, "cat concatenate", "<mark>cat</mark> concatenate", 1), mutate: func(attrView *av.AttributeView) { attrView.KeyValues[1].Values[0].Text.Content = "changed" }},+ {name: "no marks", marked: source},+ {name: "nil field", marked: "<mark>cat</mark>", mutate: func(attrView *av.AttributeView) { attrView.KeyValues = append(attrView.KeyValues, nil) }},+ {name: "missing key", marked: "<mark>cat</mark>", mutate: func(attrView *av.AttributeView) { attrView.KeyValues = append(attrView.KeyValues, &av.KeyValues{}) }},+ {name: "nil view", marked: "<mark>cat</mark>", mutate: func(attrView *av.AttributeView) { attrView.Views = append(attrView.Views, nil) }},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ attrView := attributeViewSearchTestFixture()+ if test.mutate != nil {+ test.mutate(attrView)+ }+ if got := compactAttributeViewSearchContent(attrView, test.marked); got != test.marked {+ t.Fatalf("fallback changed: got %q, want %q", got, test.marked)+ }+ })+ }+}++func TestAttributeViewSearchFormattedIndexValues(t *testing.T) {+ tests := []struct {+ name, content string+ value *av.Value+ }{+ {name: "number", content: "$1,200.00", value: &av.Value{Type: av.KeyTypeNumber, Number: &av.ValueNumber{Content: 1200, FormattedContent: "$1,200.00"}}},+ {name: "date", content: "2026-10-01", value: &av.Value{Type: av.KeyTypeDate, Date: &av.ValueDate{Content: 1790812800000, FormattedContent: "2026-10-01"}}},+ {name: "multiple selections", content: "first second", value: &av.Value{Type: av.KeyTypeMSelect, MSelect: []*av.ValueSelect{{Content: "first"}, {Content: "second"}}}},+ {name: "checkbox", content: "√", value: &av.Value{Type: av.KeyTypeCheckbox, Checkbox: &av.ValueCheckbox{Checked: true}}},+ {name: "relation", content: "linked one, linked two", value: &av.Value{Type: av.KeyTypeRelation, Relation: &av.ValueRelation{Contents: []*av.Value{attributeViewSearchTestText("linked one"), attributeViewSearchTestText("linked two")}}}},+ {name: "rollup", content: "rolled one, rolled two", value: &av.Value{Type: av.KeyTypeRollup, Rollup: &av.ValueRollup{Contents: []*av.Value{attributeViewSearchTestText("rolled one"), attributeViewSearchTestText("rolled two")}}}},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ attrView := &av.AttributeView{+ Name: " DB ",+ Views: []*av.View{{Name: "First view"}, {Name: "Second view"}},+ KeyValues: []*av.KeyValues{{Key: &av.Key{Name: "Field", Type: test.value.Type}, Values: []*av.Value{nil, test.value, nil}}},+ }+ marked := "DB First view Second view Field <mark>" + util.EscapeHTML(test.content) + "</mark>"+ got := compactAttributeViewSearchContent(attrView, marked)+ if got == marked || !strings.Contains(got, `<span class="fn__code">Field</span> <mark>`+util.EscapeHTML(test.content)+`</mark>`) {+ t.Fatalf("formatted index value was not mapped: %q", got)+ }+ })+ }+}++func TestAttributeViewSearchEscapesUserContent(t *testing.T) {+ attrView := &av.AttributeView{+ Name: "<img src=x onerror=alert(1)>",+ KeyValues: []*av.KeyValues{{+ Key: &av.Key{Name: "<script>field</script>&", Type: av.KeyTypeText},+ Values: []*av.Value{attributeViewSearchTestText("before <mark>literal</mark> A&B <script>value</script> after")},+ }},+ }+ source := attrView.Name + " " + attrView.KeyValues[0].Key.Name + " " + attrView.KeyValues[0].Values[0].String(true)+ marked := strings.Replace(util.EscapeHTML(source), "A&B", "<mark>A&B</mark>", 1)+ got := compactAttributeViewSearchContent(attrView, marked)+ if got == marked || !strings.Contains(got, "<mark>A&B</mark>") {+ t.Fatalf("escaped match was not mapped: %q", got)+ }+ for _, raw := range []string{"<img", "<script>", "<mark>literal</mark>"} {+ if strings.Contains(got, raw) {+ t.Errorf("unescaped user markup %q in %q", raw, got)+ }+ }+ if strings.Count(got, "<mark>") != 1 || strings.Count(got, "</mark>") != 1 {+ t.Fatalf("unexpected generated highlights: %q", got)+ }+}++func TestAttributeViewSearchPartHTMLBounds(t *testing.T) {+ prefix, suffix := strings.Repeat("前🙂&", 40), strings.Repeat("后🙂&", 40)+ text := prefix + "<hit>" + suffix+ part := &attributeViewSearchPart{text: text, ranges: []attributeViewSearchRange{{len(prefix), len(prefix) + len("<hit>")}}}+ got := attributeViewSearchPartHTML(part)+ prefixRunes, suffixRunes := []rune(prefix), []rune(suffix)+ want := "..." + util.EscapeHTML(string(prefixRunes[len(prefixRunes)-32:])) + "<mark><hit></mark>" + util.EscapeHTML(string(suffixRunes[:64])) + "..."+ if got != want || !utf8.ValidString(got) {+ t.Fatalf("invalid or unbounded snippet: got %q, want %q", got, want)+ }++ longMatch := strings.Repeat("界", 100)+ part = &attributeViewSearchPart{text: "hit " + longMatch, ranges: []attributeViewSearchRange{{0, 3}, {4, 4 + len(longMatch)}}}+ got = attributeViewSearchPartHTML(part)+ if want = "<mark>hit</mark> <mark>" + longMatch + "</mark>"; got != want {+ t.Fatalf("match crossing context edge was split: %q", got)+ }++ part = &attributeViewSearchPart{text: "hit " + strings.Repeat("x", 100) + " distant", ranges: []attributeViewSearchRange{{0, 3}, {105, 112}}}+ got = attributeViewSearchPartHTML(part)+ if strings.Contains(got, "distant") || strings.Count(got, "<mark>") != 1 || !strings.HasSuffix(got, "...") {+ t.Fatalf("distant match escaped the context limit: %q", got)+ }+}++func TestAttributeViewSearchCompactFieldLimit(t *testing.T) {+ attrView := &av.AttributeView{Name: "DB"}+ var marked strings.Builder+ marked.WriteString("DB")+ for _, field := range []string{"one", "two", "three", "four", "five", "six", "seven", "eight"} {+ attrView.KeyValues = append(attrView.KeyValues, &av.KeyValues{Key: &av.Key{Name: field, Type: av.KeyTypeText}, Values: []*av.Value{attributeViewSearchTestText("match")}})+ marked.WriteString(" " + field + " <mark>match</mark>")+ }+ got := compactAttributeViewSearchContent(attrView, marked.String())+ if strings.Count(got, `class="fn__code"`) != 6 || strings.Contains(got, "seven") || strings.Contains(got, "eight") {+ t.Fatalf("unexpected field limit: %q", got)+ }+}++func attributeViewSearchTestFixture() *av.AttributeView {+ return &av.AttributeView{+ Name: "Contacts",+ Views: []*av.View{{Name: "All people"}},+ KeyValues: []*av.KeyValues{+ {Key: &av.Key{Name: "Title", Type: av.KeyTypeBlock}, Values: []*av.Value{+ {Type: av.KeyTypeBlock, BlockID: "row-a", Block: &av.ValueBlock{Content: "Project Apollo"}},+ {Type: av.KeyTypeBlock, BlockID: "row-b", Block: &av.ValueBlock{Content: "Project Borealis"}},+ }},+ {Key: &av.Key{Name: "Status", Type: av.KeyTypeText}, Values: []*av.Value{+ {Type: av.KeyTypeText, BlockID: "row-a", Text: &av.ValueText{Content: "cat"}},+ nil,+ {Type: av.KeyTypeText, BlockID: "row-b", Text: &av.ValueText{Content: "concatenate"}},+ }},+ },+ }+}++func attributeViewSearchTestText(content string) *av.Value {+ return &av.Value{Type: av.KeyTypeText, Text: &av.ValueText{Content: content}}+}