Skip to content

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

:bug: Preserve database card clicks and reuse row previews

Daniela632e8540e91
diff --git a/app/src/protyle/render/av/databaseRowReuse.test.ts b/app/src/protyle/render/av/databaseRowReuse.test.ts
new file mode 100644
index 0000000000..cf2999401c
--- /dev/null
+++ b/app/src/protyle/render/av/databaseRowReuse.test.ts
@@ -0,0 +1,128 @@
+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, ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import type {IDatabaseRowOpenData} from "./openDatabaseRow";
+
+const {parse} = require("ifdef-loader/preprocessor");
+const compile = (source: string) => transpileModule(source, {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+const utilSource = createSourceFile("util.ts", readFileSync("src/editor/util.ts", "utf8"), ScriptTarget.ES2021, true);
+const utilCode = compile(utilSource.statements.filter(statement => isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(item => ["openFile", "isSameCustomTab", "getUnInitTab"]
+ .includes(item.name.getText(utilSource)))).map(statement => statement.getText(utilSource)).join("\n"));
+const rowCode = compile(parse(readFileSync("src/protyle/render/av/openDatabaseRow.ts", "utf8"),
+ {MOBILE: false, BROWSER: true}, false, true));
+
+// 执行条目入口和通用页签查找,覆盖已加载及布局恢复后尚未初始化的预览。
+const setup = (restored = false) => {
+ let created = 0;
+ let switched = 0;
+ interface TestPane {
+ children: {headElement: object}[];
+ parent: {children: unknown[]};
+ element: {getAttribute(): string};
+ split(): TestPane;
+ addTab(): void;
+ showHeading(): void;
+ switchTab(head: TestTab["headElement"]): void;
+ }
+ interface TestTab {
+ parent: TestPane;
+ model?: Custom;
+ headElement: {getAttribute(name: string): string};
+ }
+ const models: Custom[] = [];
+ const tabs: TestTab[] = [];
+ const wnd: TestPane = {
+ children: [{headElement: {}}], parent: {children: []}, element: {getAttribute: () => "pane"},
+ split: () => wnd, addTab() {}, showHeading() {},
+ switchTab(head: {getAttribute: (name: string) => string}) {
+ switched++;
+ const tab = tabs.find(item => item.headElement === head);
+ if (!tab.model) {
+ const data = JSON.parse(head.getAttribute("data-initdata"));
+ tab.model = new Custom(data.customModelData);
+ tab.model.parent = tab;
+ models.push(tab.model);
+ }
+ },
+ };
+ class Custom {
+ public type = "siyuan-database-row";
+ public parent: TestTab;
+ public element = {dispatchEvent() {}, querySelector: () => ({})};
+ constructor(public data: IDatabaseRowOpenData) {}
+ public update() {}
+ }
+ const makeTab = (data: IDatabaseRowOpenData, lazy = false): TestTab => {
+ const tab: TestTab = {parent: wnd, model: lazy ? undefined : new Custom(data),
+ headElement: {getAttribute: (name: string) => name === "data-initdata" && lazy ? JSON.stringify({
+ instance: "Custom", customModelType: "siyuan-database-row", customModelData: data,
+ }) : null}};
+ if (tab.model) {
+ tab.model.parent = tab;
+ models.push(tab.model);
+ }
+ tabs.push(tab);
+ return tab;
+ };
+ const data: IDatabaseRowOpenData = {avID: "database", databaseBlockID: "carrier", notebookID: "notebook",
+ itemID: "row", valueID: "value", title: "Entry", isDetached: true};
+ if (restored) {
+ makeTab(data, true);
+ }
+ const siyuan = {config: {editor: {databaseAttrShow: true}}, languages: {untitled: "Untitled"}, layout: {}};
+ const common = {
+ window: {siyuan},
+ document: {querySelectorAll: (): Element[] => [], querySelector: () => wnd.element},
+ HTMLElement: class {}, CustomEvent: class {},
+ };
+ const util = {openFile: undefined as typeof import("../../../editor/util").openFile};
+ runInNewContext(utilCode, {...common, exports: util, clearOBG() {},
+ getAllModels: () => ({custom: models}), getAllTabs: () => tabs, pdfIsLoading: () => false,
+ getInstanceById: () => wnd, shouldCheckOtherWindows: () => false,
+ newTab: (options: IOpenFileOptions) => { created++; return makeTab(options.custom.data); },
+ });
+ const api = {} as typeof import("./openDatabaseRow");
+ const dependencies: Record<string, unknown> = {
+ "../../../editor/util": util, "../../../layout/dock/Custom": {Custom},
+ "../../../layout/util": {saveLayout() {}},
+ "./databaseRowNavigation": {getDatabaseRowNavigation: (): undefined => undefined, mountDatabaseRowNavigation() {}},
+ };
+ runInNewContext(rowCode, {...common, exports: api, require: (name: string) => dependencies[name] || {}});
+ return {data, siyuan, tabs, created: () => created, switched: () => switched,
+ open: (row = data, options?: Parameters<typeof api.openDatabaseRowByData>[2]) =>
+ api.openDatabaseRowByData({app: {}} as Pick<IProtyle, "app">, row, options)};
+};
+
+for (const restored of [false, true]) {
+ test(`ordinary row clicks reuse ${restored ? "restored" : "loaded"} previews by database and item identity`, async () => {
+ const h = setup(restored);
+ assert.equal(await h.open(), true);
+ const opened = h.tabs[0];
+ assert.equal(await h.open({...h.data, title: "Renamed", navigation: {viewID: "other-view", query: "text"}}), true);
+ assert.equal(h.tabs.length, 1);
+ assert.equal(h.tabs[0], opened);
+ assert.equal(opened.model.data.title, "Renamed");
+ assert.equal(h.created(), restored ? 0 : 1);
+ assert.equal(h.switched(), restored ? 2 : 1);
+ await h.open({...h.data, itemID: "other-row"});
+ await h.open({...h.data, avID: "other-database"});
+ assert.equal(h.tabs.length, 3);
+ });
+}
+
+test("standalone bound rows and panel-preserving opens retain preview reuse", async () => {
+ const h = setup();
+ const bound = {...h.data, isDetached: false, boundBlockID: "document"};
+ h.siyuan.config.editor.databaseAttrShow = false;
+ await h.open(bound);
+ await h.open(bound);
+ h.siyuan.config.editor.databaseAttrShow = true;
+ await h.open(bound, {standalone: true, keepAVPanel: true});
+ assert.equal(h.created(), 1);
+ assert.equal(h.tabs.length, 1);
+});
diff --git a/app/src/protyle/render/av/openDatabaseRow.ts b/app/src/protyle/render/av/openDatabaseRow.ts
index 36f617ce57..c042903140 100644
--- a/app/src/protyle/render/av/openDatabaseRow.ts
+++ b/app/src/protyle/render/av/openDatabaseRow.ts
@@ -393,7 +393,6 @@ export const openDatabaseRowByData = async (protyle: Pick<IProtyle, "app">, data
app: protyle.app,
position: options?.position || "right",
removeCurrentTab: options && !options.keepAVPanel ? undefined : false,
- openNewTab: options ? options.keepAVPanel ? false : undefined : true,
keepAVPanel: options?.keepAVPanel,
custom: {
id: "siyuan-database-row",
diff --git a/app/src/protyle/render/av/row.ts b/app/src/protyle/render/av/row.ts
index 042badb732..254d0a61df 100644
--- a/app/src/protyle/render/av/row.ts
+++ b/app/src/protyle/render/av/row.ts
@@ -74,7 +74,7 @@ export const getRowHTML = (options: {
html += getCardCoverHTML(coverClass, galleryRow.coverURL, getCompressURL(galleryRow.coverURL),
galleryData.fitImage, getCardCoverSource(galleryData), galleryRow.coverPosition);
} else if (galleryRow.coverContent) {
- html += `<div class="${coverClass}"><div class="av__gallery-content">${galleryRow.coverContent}</div><div></div></div>`;
+ html += `<div class="${coverClass}"><div class="av__gallery-content" inert>${galleryRow.coverContent}</div><div></div></div>`;
} else {
html += `<div class="${coverClass}"></div>`;
}
@@ -145,7 +145,7 @@ ${cell.color ? `color:${cell.color};` : ""}">${renderCell(cell.value, options.ro
html += getCardCoverHTML(coverClass, kanbanRow.coverURL, getCompressURL(kanbanRow.coverURL),
kanbanData.fitImage, getCardCoverSource(kanbanData), kanbanRow.coverPosition);
} else if (kanbanRow.coverContent.trim()) {
- html += `<div class="${coverClass}"><div class="av__gallery-content">${kanbanRow.coverContent}</div><div></div></div>`;
+ html += `<div class="${coverClass}"><div class="av__gallery-content" inert>${kanbanRow.coverContent}</div><div></div></div>`;
}
}
html += `<div class="${getCardFieldsClass(kanbanData.cardLayout)}">`;
diff --git a/app/tests/avCardPreview.test.js b/app/tests/avCardPreview.test.js
new file mode 100644
index 0000000000..886de8ad56
--- /dev/null
+++ b/app/tests/avCardPreview.test.js
@@ -0,0 +1,158 @@
+const assert = require("node:assert/strict");
+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");
+const path = require("node:path");
+const os = require("node:os");
+
+const runCases = (sources, mobile) => {
+ const assert = require("node:assert/strict");
+ const opened = [];
+ const primary = {id: "value", value: {keyID: "primary", block: {id: "document", content: "Title"}}};
+ window.siyuan = {languages: {}};
+ const dependencies = {
+ "./conditionalColor": {getConditionalItemStyle: () => ""},
+ "../../../util/escape": {escapeAttr: value => value},
+ "../../../util/image": {getCompressURL: value => value},
+ "../../../util/imageURL": {isBrowserRenderableImagePath: () => true},
+ "./attributeValue": {getAVTemplateInteractiveElement: () => undefined},
+ "../../util/compatibility": {isOnlyMeta: event => event.metaKey || event.ctrlKey},
+ "./coverPosition": {isCardCoverPositioning: () => false},
+ "./virtualScroll": {getAVPrimaryCell: (block, itemID) => {
+ assert.equal(block.dataset.nodeId, "database");
+ assert.equal(itemID, "row");
+ return primary;
+ }},
+ "./cellValue": {cloneAVCellValueSnapshot: value => JSON.parse(JSON.stringify(value))},
+ "./openDatabaseRow": {openDatabaseRowByData: (_protyle, data) => opened.push(data)},
+ };
+ const load = name => {
+ if (!dependencies[name]) {
+ const exports = {};
+ new Function("require", "exports", sources[name])(id => sources[id] ? load(id) : dependencies[id] || {}, exports);
+ dependencies[name] = exports;
+ }
+ return dependencies[name];
+ };
+ const {getRowHTML} = load("./row");
+ const {avClick} = load("./action");
+ const host = document.createElement("div");
+ host.className = "protyle-wysiwyg";
+ host.style.width = mobile ? "360px" : "800px";
+ document.body.append(host);
+ const protyle = {notebookId: "notebook"};
+ for (const type of ["gallery", "kanban"]) {
+ const data = {fields: [{id: "primary", type: "block", hidden: true}], coverFrom: 1,
+ cardAspectRatio: 0, displayEmptyFields: true};
+ for (const cover of [
+ {coverContent: '<div data-node-id="preview" data-type="NodeParagraph" class="p"><div contenteditable="false">Preview <span data-type="block-ref" data-id="other">reference</span></div></div><a href="#other">Link</a><button>Button</button><input value="Preview input">'},
+ {coverURL: "assets/cover.png"},
+ {},
+ ]) {
+ host.innerHTML = `<div class="av" data-node-id="database" data-av-id="av" data-type="NodeAttributeView" data-av-type="${type}"><div class="av__gallery">${getRowHTML({data, row: {id: "row", values: [], coverContent: "", ...cover}, rowIndex: 0, type})}</div></div>`;
+ const block = host.firstElementChild;
+ const coverElement = host.querySelector(".av__gallery-cover");
+ const preview = host.querySelector(".av__gallery-content");
+ if (!coverElement) {
+ assert.equal(type, "kanban");
+ assert.deepEqual(cover, {});
+ continue;
+ }
+ if (preview) {
+ // 模拟主题将摘要提升到遮罩之上,验证事件和焦点仍由外层卡片承接。
+ preview.style.position = "relative";
+ preview.style.zIndex = "1";
+ for (const control of preview.querySelectorAll("a, button, input")) {
+ control.style.pointerEvents = "auto";
+ control.focus();
+ assert.notEqual(document.activeElement, control);
+ }
+ }
+ const rect = coverElement.getBoundingClientRect();
+ assert.ok(rect.width > 0 && rect.height > 0);
+ for (const offset of [12, 35, 65]) {
+ const target = document.elementFromPoint(rect.left + 35, rect.top + offset);
+ assert.ok(coverElement.contains(target));
+ assert.ok(!preview?.contains(target), "preview blocks and controls cannot capture pointer input");
+ const before = opened.length;
+ const event = new MouseEvent("click", {bubbles: true, cancelable: true});
+ block.onclick = event => avClick(protyle, event);
+ target.dispatchEvent(event);
+ if (type === "gallery") {
+ assert.equal(opened.length, before + 1);
+ assert.equal(opened.at(-1).boundBlockID, "document");
+ assert.equal(opened.at(-1).itemID, "row");
+ assert.equal(event.defaultPrevented, true);
+ }
+ }
+ if (preview) {
+ // 对照相同布局,摘要恢复交互后会遮住封面并截获命中。
+ preview.inert = false;
+ const target = document.elementFromPoint(rect.left + 35, rect.top + 12);
+ assert.ok(preview.contains(target));
+ }
+ }
+ }
+};
+
+const runElectron = async () => {
+ const {app, BrowserWindow} = require("electron");
+ app.setPath("userData", process.argv[2]);
+ app.commandLine.appendSwitch("disable-gpu");
+ await app.whenReady();
+ const win = new BrowserWindow({show: false, width: 1100, height: 900,
+ webPreferences: {nodeIntegration: true, contextIsolation: false}});
+ let exitCode = 0;
+ try {
+ const ts = require("typescript");
+ const {parse} = require("ifdef-loader/preprocessor");
+ for (const mobile of [false, true]) {
+ const files = {"./row": "render/av/row", "./action": "render/av/action",
+ "./cover": "render/av/cover", "./gallery/cardLayout": "render/av/gallery/cardLayout",
+ "../../util/hasClosest": "util/hasClosest"};
+ const sources = Object.fromEntries(Object.entries(files).map(([name, file]) => [name,
+ ts.transpileModule(parse(readFileSync(path.join(__dirname, `../src/protyle/${file}.ts`), "utf8"),
+ {MOBILE: mobile, BROWSER: true}, false, true), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},
+ }).outputText]));
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ await win.webContents.insertCSS(require("sass").compile(path.join(__dirname,
+ `../src/assets/scss/${mobile ? "mobile" : "base"}.scss`), {logger: {warn() {}}}).css);
+ const error = await win.webContents.executeJavaScript(`(() => {
+ try { (${runCases.toString()})(${JSON.stringify(sources)}, ${mobile}); return ""; }
+ catch (error) { return error.stack; }
+ })()`);
+ assert.equal(error, "");
+ }
+ console.log("AV card preview input cases passed");
+ } catch (error) {
+ console.error(error);
+ exitCode = 1;
+ } finally {
+ win.destroy();
+ app.exit(exitCode);
+ }
+};
+
+if (process.versions.electron && process.type === "browser") {
+ runElectron().catch(error => {
+ console.error(error);
+ require("electron").app.exit(1);
+ });
+} else {
+ require("node:test").test("card content previews preserve pointer opening and reject focus on desktop and mobile", {
+ 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-av-card-preview-"));
+ try {
+ const {stdout} = await require("node:util").promisify(require("node:child_process").execFile)(
+ require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 40000});
+ assert.match(stdout, /AV card preview input cases passed/);
+ } finally {
+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));
+ assert.ok(path.basename(profile).startsWith("siyuan-av-card-preview-"));
+ rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
+ }
+ });
+}