Skip to content

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

:sparkles: Support navigation between database row previews https://github.com/siyuan-note/siyuan/issues/20407

Daniel49c188a3b281
diff --git a/app/src/editor/util.ts b/app/src/editor/util.ts
index b861c2f503..c12b4c0f02 100644
--- a/app/src/editor/util.ts
+++ b/app/src/editor/util.ts
@@ -597,7 +597,7 @@ const switchEditor = (editor: Editor, options: IOpenFileOptions, allModels: IMod
}
};
-const newTab = (options: IOpenFileOptions) => {
+export const newTab = (options: IOpenFileOptions) => {
let tab: Tab;
if (options.assetPath) {
const suffix = getAssetExtension(options.assetPath).toLowerCase();
diff --git a/app/src/layout/Wnd.ts b/app/src/layout/Wnd.ts
index da09861e66..7cbb3feefb 100644
--- a/app/src/layout/Wnd.ts
+++ b/app/src/layout/Wnd.ts
@@ -780,7 +780,7 @@ export class Wnd {
}
}
- public addTab(tab: Tab, keepCursor = false, isSaveLayout = true, activeTime?: string) {
+ public addTab(tab: Tab, keepCursor = false, isSaveLayout = true, activeTime?: string, replaceTabID?: string) {
if (keepCursor) {
tab.headElement?.classList.remove("item--focus");
tab.panelElement.classList.add("fn__none");
@@ -842,6 +842,11 @@ export class Wnd {
tab.callback(tab);
}
+ // 预览切换先移除被替换的页签,再检查数量上限,避免关闭无关页签。
+ if (replaceTabID && replaceTabID !== tab.id) {
+ this.removeTab(replaceTabID, false, false, false);
+ }
+
// 移除 centerLayout 中的 empty
if (this.parent.type === "center" && this.children.length === 2 && !this.children[0].headElement) {
this.removeTab(this.children[0].id);
diff --git a/app/src/layout/replaceTab.test.ts b/app/src/layout/replaceTab.test.ts
new file mode 100644
index 0000000000..cf00c82def
--- /dev/null
+++ b/app/src/layout/replaceTab.test.ts
@@ -0,0 +1,39 @@
+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";
+
+test("preview replacement removes the old tab before enforcing the tab limit", () => {
+ const exports = {} as {Wnd: {prototype: object}};
+ runInNewContext(transpileModule(readFileSync("src/layout/Wnd.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {exports, window: {siyuan: {config: {fileTree: {maxOpenTabCount: 2}}}}, require: (name: string) => {
+ if (name === "../protyle/util/compatibility") { return {isPhablet: () => false}; }
+ if (name === "../window/setHeader") { return {setModelsHash() {}}; }
+ return {};
+ }});
+ const node = {
+ classList: {contains: () => false, add() {}, remove() {}},
+ querySelector: (): unknown => node,
+ after() {}, append() {}, addEventListener() {}, setAttribute() {},
+ };
+ const tab = (id: string) => ({id, headElement: {...node, nextElementSibling: null as HTMLElement}, panelElement: node});
+ for (const replace of [true, false]) {
+ const wnd = Object.create(exports.Wnd.prototype);
+ wnd.children = [tab("unrelated"), tab("old-preview")];
+ wnd.headersElement = {parentElement: node, childElementCount: 2, children: [node, node]};
+ wnd.element = {querySelector: () => ({...node, children: [node, node, node]})};
+ wnd.parent = {type: "center"};
+ let limited = false;
+ wnd.removeOverCounter = () => { limited = true; };
+ wnd.removeTab = (id: string) => {
+ wnd.children = wnd.children.filter((item: {id: string}) => item.id !== id);
+ };
+ wnd.addTab(tab("new-preview"), false, false, undefined, replace ? "old-preview" : undefined);
+ assert.equal(limited, !replace);
+ assert.equal(wnd.children.some((item: {id: string}) => item.id === "unrelated"), true);
+ assert.equal(wnd.children.some((item: {id: string}) => item.id === "old-preview"), !replace);
+ assert.equal(wnd.children.some((item: {id: string}) => item.id === "new-preview"), true);
+ }
+});
diff --git a/app/src/protyle/render/av/databaseRowNavigation.test.ts b/app/src/protyle/render/av/databaseRowNavigation.test.ts
new file mode 100644
index 0000000000..6349919f34
--- /dev/null
+++ b/app/src/protyle/render/av/databaseRowNavigation.test.ts
@@ -0,0 +1,102 @@
+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";
+import type {IDatabaseRowOpenData} from "./openDatabaseRow";
+
+const data: IDatabaseRowOpenData = {
+ avID: "database", databaseBlockID: "carrier", notebookID: "notebook", itemID: "current",
+ valueID: "current-value", title: "Current", isDetached: true,
+ navigation: {viewID: "view", query: "filter", groupID: "group", calendarRange: {start: 1, end: 10, timeZone: "UTC"}},
+};
+const row = (id: string, detached = true) => ({id, cells: [{id: id + "-value", valueType: "block",
+ value: {type: "block", isDetached: detached, block: {id: detached ? undefined : id + "-block", content: id}}}]});
+
+const load = (fetch: (request: Record<string, any>) => unknown, stored?: IAV) => {
+ const exports = {} as typeof import("./databaseRowNavigation");
+ runInNewContext(transpileModule(readFileSync("src/protyle/render/av/databaseRowNavigation.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {exports, require: (name: string) => {
+ if (name === "../../../util/fetch") {
+ return {fetchSyncPost: async (url: string, request: Record<string, any>) => {
+ assert.equal(url, "/api/av/renderAttributeView");
+ assert.equal(request.blockID, "carrier");
+ assert.equal(request.viewID, "view");
+ assert.equal(request.query, "filter");
+ assert.equal(request.createIfNotExist, false);
+ assert.equal(request.calendarRange.timeZone, "UTC");
+ return fetch(request);
+ }};
+ }
+ if (name === "./renderData") { return {isAVRenderData: (value: IAV) => !!value?.view}; }
+ if (name === "./virtualScroll") { return {getAVData: () => stored}; }
+ return {};
+ }});
+ return exports;
+};
+
+test("row navigation uses the located window beyond the source page and preserves bound row identity", async () => {
+ const api = load(request => {
+ assert.equal(request.targetItemID, "current");
+ return {code: 0, data: {view: {rows: [row("previous", false), row("current"), row("next")], rowCount: 500},
+ target: {status: "visible", index: 249, offset: 248}}};
+ });
+ const [previous, next] = await api.getDatabaseRowNeighbors(data);
+ assert.equal(previous.itemID, "previous");
+ assert.equal(previous.boundBlockID, "previous-block");
+ assert.equal(previous.isDetached, false);
+ assert.equal(next.itemID, "next");
+ assert.equal(next.isDetached, true);
+ assert.equal(next.valueID, "next-value");
+});
+
+test("group boundaries skip hidden and empty groups and fetch only the previous group's last row", async () => {
+ let requests = 0;
+ const api = load(request => {
+ requests++;
+ if (request.groupPaging) {
+ assert.equal(request.targetItemID, undefined);
+ assert.equal(request.groupPaging.before.page, 301);
+ assert.equal(request.groupPaging.before.pageSize, 1);
+ return {code: 0, data: {view: {groups: [{id: "before", rows: [row("last")]}]}}};
+ }
+ return {code: 0, data: {view: {groups: [
+ {id: "before", rows: [row("first")], rowCount: 301},
+ {id: "hidden", rows: [row("hidden")], rowCount: 1, groupHidden: 2},
+ {id: "group", rows: [row("current")], rowCount: 1},
+ {id: "empty", rows: [], rowCount: 0},
+ {id: "after", cards: [{id: "next", values: row("next").cells}], cardCount: 10},
+ ]}, target: {status: "visible", groupID: "group"}}};
+ });
+ const [previous, next] = await api.getDatabaseRowNeighbors(data);
+ assert.equal(previous.itemID, "last");
+ assert.equal(previous.navigation.groupID, "before");
+ assert.equal(next.itemID, "next");
+ assert.equal(next.navigation.groupID, "after");
+ assert.equal(requests, 2);
+});
+
+test("first and last rows stop without wrapping and unavailable rows cannot navigate", async () => {
+ for (const status of ["visible", "filtered", "itemNotFound", "groupHidden"]) {
+ const api = load(() => ({code: 0, data: {view: {rows: [row("current")], rowCount: 1}, target: {status}}}));
+ assert.ok((await api.getDatabaseRowNeighbors(data)).every(item => !item));
+ }
+ for (const response of [{code: -1}, {code: 0, data: {error: "viewNotFound"}}]) {
+ assert.equal((await load(() => response).getDatabaseRowNeighbors(data)).length, 0);
+ }
+});
+
+test("navigation context captures the source view and search without enabling live navigation in history", () => {
+ const stored = {id: "database", viewID: "view", view: {calendarRange: data.navigation.calendarRange}} as IAV;
+ const block = {querySelector: (selector: string) => selector.includes("av-search") ? {textContent: " filter "} :
+ {closest: () => ({dataset: {groupId: "group"}})}};
+ const source = {wysiwyg: {element: {querySelector: () => block}}, options: {}} as unknown as IProtyle;
+ const api = load(() => { throw new Error("No request expected"); }, stored);
+ const context = api.getDatabaseRowNavigation(source, data);
+ assert.equal(context.viewID, "view");
+ assert.equal(context.query, "filter");
+ assert.equal(context.groupID, "group");
+ source.options.history = {created: "archive"};
+ assert.equal(api.getDatabaseRowNavigation(source, data), undefined);
+});
diff --git a/app/src/protyle/render/av/databaseRowNavigation.ts b/app/src/protyle/render/av/databaseRowNavigation.ts
new file mode 100644
index 0000000000..5005dfe41a
--- /dev/null
+++ b/app/src/protyle/render/av/databaseRowNavigation.ts
@@ -0,0 +1,148 @@
+import {fetchSyncPost} from "../../../util/fetch";
+import {escapeAttr} from "../../../util/escape";
+import {isAVRenderData} from "./renderData";
+import {getAVData} from "./virtualScroll";
+import type {IDatabaseRowOpenData} from "./openDatabaseRow";
+
+export interface IDatabaseRowNavigation {
+ viewID: string;
+ query: string;
+ groupID?: string;
+ calendarRange?: IAVCalendarRange;
+}
+
+export const getDatabaseRowNavigation = (source: Partial<IProtyle>, data: IDatabaseRowOpenData) => {
+ if (source.options?.history?.created || source.options?.history?.snapshot) {
+ return;
+ }
+ const block = source.wysiwyg?.element.querySelector<HTMLElement>(`[data-node-id="${data.databaseBlockID}"]`);
+ const av = block && getAVData(block);
+ if (!av || av.id !== data.avID) {
+ return;
+ }
+ return {
+ viewID: av.viewID,
+ query: block.querySelector('[data-type="av-search"]')?.textContent.trim() || "",
+ groupID: block.querySelector(`[data-id="${data.itemID}"]`)?.closest<HTMLElement>(".av__body")?.dataset.groupId,
+ calendarRange: (av.view as IAVTable).calendarRange,
+ };
+};
+
+const getItems = (view: IAVView): Array<IAVRow | IAVGalleryItem> =>
+ (view as IAVTable).rows || (view as IAVGallery).cards || [];
+
+const getCount = (view: IAVView) => (view as IAVTable).rowCount ?? (view as IAVGallery).cardCount ?? 0;
+
+export const getDatabaseRowNeighbors = async (data: IDatabaseRowOpenData) => {
+ const navigation = data.navigation;
+ if (!navigation) {
+ return [];
+ }
+ const request = {
+ id: data.avID, blockID: data.databaseBlockID, viewID: navigation.viewID,
+ query: navigation.query, calendarRange: navigation.calendarRange, createIfNotExist: false,
+ page: 1, pageSize: 1,
+ };
+ // 定位窗口包含当前条目的前后行,避免只在已渲染的分页或虚拟滚动范围内切换。
+ const response = await fetchSyncPost("/api/av/renderAttributeView", {
+ ...request, targetItemID: data.itemID, targetGroupID: navigation.groupID,
+ });
+ if (response.code !== 0 || !isAVRenderData(response.data) || response.data.target?.status !== "visible") {
+ return [];
+ }
+ const av: IAV = response.data;
+ const groups = av.view.groups?.length ? av.view.groups.filter(group => !group.groupHidden && getCount(group) > 0) : [av.view];
+ const groupIndex = av.view.groups?.length ? groups.findIndex(group => group.id === av.target.groupID) : 0;
+ if (groupIndex < 0) {
+ return [];
+ }
+ const items = getItems(groups[groupIndex]);
+ const index = items.findIndex(item => item.id === data.itemID);
+ if (index < 0) {
+ return [];
+ }
+ return Promise.all([-1, 1].map(async direction => {
+ let groupID = av.target.groupID;
+ let item = items[index + direction];
+ if (!item) {
+ const group = groups[groupIndex + direction];
+ if (!group) {
+ return undefined;
+ }
+ groupID = group.id;
+ if (direction > 0) {
+ item = getItems(group)[0];
+ } else {
+ // 前一分组只取末行,不加载整个分组。
+ const previous = await fetchSyncPost("/api/av/renderAttributeView", {
+ ...request, groupPaging: {[groupID]: {page: getCount(group), pageSize: 1}},
+ });
+ if (previous.code === 0 && isAVRenderData(previous.data)) {
+ const previousGroup = previous.data.view.groups?.find(candidate => candidate.id === groupID);
+ item = previousGroup && getItems(previousGroup)[0];
+ }
+ }
+ }
+ const primary = item && ("cells" in item ? item.cells : item.values)
+ .find(cell => cell.valueType === "block" || cell.value?.type === "block");
+ if (!primary?.value) {
+ return undefined;
+ }
+ return {
+ avID: data.avID, databaseBlockID: data.databaseBlockID, notebookID: data.notebookID,
+ itemID: item.id, valueID: primary.id || primary.value.id,
+ title: primary.value.block?.content || "", boundBlockID: primary.value.block?.id,
+ isDetached: primary.value.isDetached === true || !primary.value.block?.id,
+ navigation: {...navigation, groupID},
+ } satisfies IDatabaseRowOpenData;
+ }));
+};
+
+export const mountDatabaseRowNavigation = (container: Element, data: IDatabaseRowOpenData,
+ open: (data: IDatabaseRowOpenData) => Promise<boolean>) => {
+ container.querySelector(":scope > [data-database-row-navigation]")?.remove();
+ if (!data.navigation) {
+ return;
+ }
+ const toolbar = document.createElement("div");
+ toolbar.className = "block__icons";
+ toolbar.setAttribute("data-database-row-navigation", data.itemID);
+ toolbar.innerHTML = ["previous", "next"].map((name, index) =>
+ `<button type="button" disabled class="block__icon block__icon--show block__icon--touch ariaLabel" data-position="8south" aria-label="${escapeAttr(window.siyuan.languages[name])}"><svg><use xlink:href="#${index ? "iconDown" : "iconUp"}"></use></svg></button>`)
+ .join('<span class="fn__space"></span>');
+ container.prepend(toolbar);
+ const buttons = Array.from(toolbar.querySelectorAll("button"));
+ let busy = false;
+ const update = async () => {
+ try {
+ const neighbors = await getDatabaseRowNeighbors(data);
+ if (toolbar.isConnected) {
+ buttons.forEach((button, index) => { button.disabled = !neighbors[index]; });
+ }
+ } catch (error) {
+ console.warn("Failed to load database row navigation:", error);
+ }
+ };
+ buttons.forEach((button, index) => button.addEventListener("click", async () => {
+ if (busy) {
+ return;
+ }
+ busy = true;
+ buttons.forEach(item => { item.disabled = true; });
+ try {
+ // 点击时重新定位,避免筛选、排序或删除后打开过期的相邻条目。
+ const neighbors = await getDatabaseRowNeighbors(data);
+ if (toolbar.isConnected && neighbors[index]) {
+ await open(neighbors[index]);
+ }
+ } catch (error) {
+ console.warn("Failed to navigate database rows:", error);
+ } finally {
+ busy = false;
+ if (toolbar.isConnected) {
+ void update();
+ }
+ }
+ }));
+ void update();
+};
diff --git a/app/src/protyle/render/av/databaseRowPreviewNavigation.test.ts b/app/src/protyle/render/av/databaseRowPreviewNavigation.test.ts
new file mode 100644
index 0000000000..07d2ab1662
--- /dev/null
+++ b/app/src/protyle/render/av/databaseRowPreviewNavigation.test.ts
@@ -0,0 +1,115 @@
+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";
+import type {IDatabaseRowOpenData} from "./openDatabaseRow";
+
+const {parse} = require("ifdef-loader/preprocessor");
+
+test("row navigation replaces only its original desktop preview across bound and detached items", async () => {
+ const callbacks = new Map<object, (data: IDatabaseRowOpenData) => Promise<boolean>>();
+ const removed: string[] = [];
+ const created: IOpenFileOptions[] = [];
+ const app = {};
+ let request: (response: unknown) => void;
+ const element = () => {
+ const root = {isConnected: true, dataset: {}, querySelector: (): unknown => root, dispatchEvent() {}};
+ return root;
+ };
+ interface TestWnd {
+ addTab(tab: TestTab, keep: boolean, save: boolean, active: string, replace: string): void;
+ removeTab(id: string): void;
+ }
+ interface TestTab {
+ id: string;
+ parent: TestWnd;
+ model: Custom | Editor;
+ panelElement: ReturnType<typeof element>;
+ }
+ const wnd: TestWnd = {
+ addTab(tab: ReturnType<typeof makeTab>, _keep: boolean, _save: boolean, _active: string, replace: string) {
+ tab.parent = wnd;
+ wnd.removeTab(replace);
+ },
+ removeTab(id: string) { removed.push(id); },
+ };
+ class Custom {
+ public app = app;
+ public element = element();
+ public data = {};
+ public parent: ReturnType<typeof makeTab>;
+ public update() {}
+ }
+ class Editor {
+ public app = app;
+ public parent: ReturnType<typeof makeTab>;
+ public editor = {protyle: {element: element(), contentElement: {scrollTop: 20}, upload: {isUploading: false},
+ databaseAttributePanel: {expand() {}, afterRender() {}}}};
+ }
+ const makeTab = (id: string, model: Custom | Editor): TestTab => {
+ const tab = {id, parent: wnd, model, panelElement: element()};
+ model.parent = tab;
+ return tab;
+ };
+ const initial = new Custom();
+ makeTab("initial", initial);
+ let latest: ReturnType<typeof makeTab>;
+ const modules: Record<string, unknown> = {
+ "../../../layout/dock/Custom": {Custom}, "../../../editor": {Editor},
+ "../../../editor/util": {
+ openFile: async (options: IOpenFileOptions) => { options.afterOpen(initial as never); return initial.parent; },
+ newTab: (options: IOpenFileOptions) => {
+ created.push(options);
+ latest = makeTab("new-" + created.length, options.custom ? new Custom() : new Editor());
+ return latest;
+ },
+ },
+ "../../../util/fetch": {fetchSyncPost: () => new Promise(resolve => { request = resolve; })},
+ "../../../dialog/message": {showMessage() {}},
+ "./rowReadonly": {inheritDatabaseRowReadonly() {}},
+ "./databaseRowNavigation": {
+ getDatabaseRowNavigation: (): undefined => undefined,
+ mountDatabaseRowNavigation: (root: object, _data: unknown, open: (data: IDatabaseRowOpenData) => Promise<boolean>) => callbacks.set(root, open),
+ },
+ };
+ const exports = {} as typeof import("./openDatabaseRow");
+ runInNewContext(transpileModule(parse(readFileSync("src/protyle/render/av/openDatabaseRow.ts", "utf8"),
+ {MOBILE: false, BROWSER: true}, false, true), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {exports, require: (name: string) => modules[name] || {},
+ window: {siyuan: {config: {editor: {databaseAttrShow: true}}, languages: {untitled: "Untitled"}}},
+ CustomEvent: class { constructor(public type: string) {} },
+ });
+ const data: IDatabaseRowOpenData = {avID: "av", databaseBlockID: "carrier", notebookID: "notebook",
+ itemID: "row", valueID: "value", title: "Row", isDetached: true, navigation: {viewID: "view", query: ""}};
+ await exports.openDatabaseRowByData({app} as Pick<IProtyle, "app">, data);
+ const move = callbacks.get(initial.element)({...data, isDetached: false, boundBlockID: "bound"});
+ assert.equal(removed.length, 0);
+ request({code: 0, data: {rootID: "another-document", rootTitle: "Document"}});
+ assert.equal(await move, true);
+ assert.deepEqual(removed, ["initial"]);
+ assert.equal(latest.parent, wnd);
+ assert.equal(created[0].id, "bound");
+ assert.equal(created[0].rootID, "another-document");
+ assert.equal(created[0].zoomIn, true);
+ const bound = latest.model as Editor;
+ bound.editor.protyle.upload.isUploading = true;
+ assert.equal(await callbacks.get(bound.editor.protyle.element)(data), false);
+ assert.equal(created.length, 1);
+ bound.editor.protyle.upload.isUploading = false;
+ assert.equal(await callbacks.get(bound.editor.protyle.element)(data), true);
+ assert.deepEqual(removed, ["initial", "new-1"]);
+ assert.equal(created[1].custom.data.itemID, "row");
+ assert.equal(created[1].custom.data.navigation.viewID, "view");
+ const detached = latest.model as Custom;
+ const failed = callbacks.get(detached.element)({...data, isDetached: false, boundBlockID: "denied"});
+ request({code: -1});
+ assert.equal(await failed, false);
+ assert.equal(removed.length, 2);
+ const closed = callbacks.get(detached.element)({...data, isDetached: false, boundBlockID: "bound"});
+ latest.panelElement.isConnected = false;
+ request({code: 0, data: {rootID: "document"}});
+ assert.equal(await closed, false);
+ assert.equal(created.length, 2);
+});
diff --git a/app/src/protyle/render/av/openDatabaseRow.ts b/app/src/protyle/render/av/openDatabaseRow.ts
index b013aeb8be..09f37434b8 100644
--- a/app/src/protyle/render/av/openDatabaseRow.ts
+++ b/app/src/protyle/render/av/openDatabaseRow.ts
@@ -5,17 +5,20 @@ import {Dialog} from "../../../dialog";
import {renderAVAttribute} from "./blockAttr";
import {Protyle} from "../../index";
/// #else
-import {openFile, openFileById} from "../../../editor/util";
+import {newTab, openFile, openFileById} from "../../../editor/util";
import {Editor} from "../../../editor";
import {getAllTabs} from "../../../layout/getAll";
import {zoomOut} from "../../../menus/protyle";
import {Custom} from "../../../layout/dock/Custom";
+import {fetchSyncPost} from "../../../util/fetch";
+import {showMessage} from "../../../dialog/message";
/// #endif
import {searchMarkRender} from "../searchMarkRender";
import {registerDatabaseRowRefresh} from "./databaseRowRefresh";
import {focusDatabasePrimary} from "./primaryFocus";
import {preserveAVBindingRange} from "./binding";
import {inheritDatabaseRowReadonly} from "./rowReadonly";
+import {getDatabaseRowNavigation, IDatabaseRowNavigation, mountDatabaseRowNavigation} from "./databaseRowNavigation";
export interface IDatabaseRowOpenData {
avID: string;
@@ -31,6 +34,7 @@ export interface IDatabaseRowOpenData {
keywords?: string[];
focusPrimary?: boolean;
bindPrimary?: boolean;
+ navigation?: IDatabaseRowNavigation;
}
const highlightDatabaseRow = (protyle: IProtyle, rootElement: HTMLElement, data: IDatabaseRowOpenData) => {
@@ -79,6 +83,7 @@ const openMobileDatabaseRow = (protyle: Pick<IProtyle, "app">, data: IDatabaseRo
},
});
const rowElement = dialog.element.querySelector<HTMLElement>(".protyle-db-row");
+ mountDatabaseRowNavigation(rowElement, data, next => openDatabaseRowByData(protyle, next));
rowElement.querySelector(".protyle-db-row__title span").textContent = title;
const render = (contextProtyle: IProtyle) => {
const previousBodyElement = rowElement.querySelector<HTMLElement>(".protyle-db-row__body");
@@ -140,6 +145,7 @@ const showDatabaseRowPreview = (model: Editor, data: IDatabaseRowOpenData, sourc
const editorProtyle = model.editor.protyle;
inheritDatabaseRowReadonly(editorProtyle, source);
editorProtyle.element.dataset.databaseRowId = data.boundBlockID || "";
+ mountDesktopDatabaseRowNavigation(model, data, source);
editorProtyle.databaseAttributePanel?.expand(data.avID);
editorProtyle.contentElement.scrollTop = 0;
editorProtyle.databaseAttributePanel?.afterRender(() => {
@@ -183,6 +189,50 @@ const getDatabaseRowPreviewTab = (blockID: string) => {
}
});
};
+
+const getCustomRowData = (data: IDatabaseRowOpenData) => ({
+ ...data, blockID: data.databaseBlockID, notebookId: data.notebookID,
+});
+
+const mountDesktopDatabaseRowNavigation = (model: Editor | Custom, data: IDatabaseRowOpenData,
+ source: Partial<IProtyle>) => {
+ const container = model instanceof Custom ? model.element.querySelector(".protyle-db-row") : model.editor.protyle.element;
+ mountDatabaseRowNavigation(container, data, async next => {
+ const tab = model.parent;
+ const wnd = tab.parent;
+ const options: IOpenFileOptions = {app: model.app};
+ if (next.isDetached || !window.siyuan.config.editor.databaseAttrShow) {
+ options.custom = {id: "siyuan-database-row", icon: "iconDatabase",
+ title: next.title || window.siyuan.languages.untitled, data: getCustomRowData(next)};
+ } else {
+ const response = await fetchSyncPost("/api/block/getBlockInfo", {id: next.boundBlockID});
+ if (response.code !== 0) {
+ return false;
+ }
+ Object.assign(options, {id: next.boundBlockID, rootID: response.data.rootID,
+ fileName: response.data.rootTitle, rootTitleEmpty: response.data.rootTitleEmpty,
+ rootIcon: response.data.rootIcon, zoomIn: next.boundBlockID !== response.data.rootID});
+ }
+ if (!tab.panelElement.isConnected || tab.model !== model) {
+ return false;
+ }
+ if (model instanceof Editor && model.editor.protyle.upload.isUploading) {
+ showMessage(window.siyuan.languages.uploading);
+ return false;
+ }
+ const opened = newTab(options);
+ // 复用来源预览所在的分屏,不依赖异步请求完成时用户正激活哪个分屏。
+ wnd.addTab(opened, false, true, undefined, tab.id);
+ if (opened.model instanceof Custom) {
+ opened.model.element.dispatchEvent(new CustomEvent("database-row-readonly", {detail: source}));
+ opened.model.update();
+ mountDesktopDatabaseRowNavigation(opened.model, next, source);
+ } else if (opened.model instanceof Editor) {
+ showDatabaseRowPreview(opened.model, next, source);
+ }
+ return true;
+ });
+};
/// #endif
export const openDatabaseRowByData = async (protyle: Pick<IProtyle, "app">, data: IDatabaseRowOpenData, options?: {
@@ -190,6 +240,7 @@ export const openDatabaseRowByData = async (protyle: Pick<IProtyle, "app">, data
keepAVPanel?: boolean,
standalone?: boolean,
}) => {
+ data = {...data, navigation: data.navigation || getDatabaseRowNavigation(protyle, data)};
const title = data.title || window.siyuan.languages.untitled;
const openStandalone = options?.standalone || data.isDetached || !window.siyuan.config.editor.databaseAttrShow;
/// #if MOBILE
@@ -206,6 +257,7 @@ export const openDatabaseRowByData = async (protyle: Pick<IProtyle, "app">, data
undefined, undefined, (editorProtyle) => {
inheritDatabaseRowReadonly(editorProtyle, protyle);
editorProtyle.element.dataset.databaseRowId = data.boundBlockID;
+ mountDatabaseRowNavigation(editorProtyle.element, data, next => openDatabaseRowByData(protyle, next));
editorProtyle.databaseAttributePanel?.expand(data.avID);
editorProtyle.contentElement.scrollTop = 0;
editorProtyle.databaseAttributePanel?.afterRender(() => {
@@ -248,6 +300,7 @@ export const openDatabaseRowByData = async (protyle: Pick<IProtyle, "app">, data
Object.assign(model.data, data, {blockID: data.databaseBlockID, notebookId: data.notebookID});
model.element.dispatchEvent(new CustomEvent("database-row-readonly", {detail: protyle}));
model.update();
+ mountDesktopDatabaseRowNavigation(model, data, protyle);
}
},
});
diff --git a/app/src/protyle/render/av/rowReadonly.test.ts b/app/src/protyle/render/av/rowReadonly.test.ts
index 482d9936d9..5e0d60af9e 100644
--- a/app/src/protyle/render/av/rowReadonly.test.ts
+++ b/app/src/protyle/render/av/rowReadonly.test.ts
@@ -52,6 +52,7 @@ const createPanel = (mobile: boolean) => {
"../../index": {Protyle},
"../../../dialog": {Dialog: class { public element = {querySelector: () => element}; }},
"../protyle/ui/padding": {getEditorHorizontalPadding: () => ({left: 0, right: 0})},
+ "./databaseRowNavigation": {getDatabaseRowNavigation: (): undefined => undefined, mountDatabaseRowNavigation() {}},
};
const load = <T>(file: string) => {
const exports = {} as T;