Skip to content

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

:bug: Keep database row previews stable and restore navigation https://github.com/siyuan-note/siyuan/issues/20407

Danielf403e72e8fba
diff --git a/app/src/editor/databaseRow.ts b/app/src/editor/databaseRow.ts
index 9e991283c4..d47364f783 100644
--- a/app/src/editor/databaseRow.ts
+++ b/app/src/editor/databaseRow.ts
@@ -7,9 +7,20 @@ import {getEditorHorizontalPadding} from "../protyle/ui/padding";
import {searchMarkRender} from "../protyle/render/searchMarkRender";
import {registerDatabaseRowRefresh} from "../protyle/render/av/databaseRowRefresh";
import {focusDatabasePrimary} from "../protyle/render/av/primaryFocus";
-import {setPanelFocus} from "../layout/util";
+import {saveLayout, setPanelFocus} from "../layout/util";
import {preserveAVBindingRange} from "../protyle/render/av/binding";
import {inheritDatabaseRowReadonly} from "../protyle/render/av/rowReadonly";
+import {IDatabaseRowOpenData, mountDesktopDatabaseRowNavigation} from "../protyle/render/av/openDatabaseRow";
+
+type TDatabaseRowData = Parameters<typeof newDatabaseRowModel>[0]["data"];
+const rowSwitchers = new WeakMap<Custom, (data: TDatabaseRowData) => Promise<boolean>>();
+const rowReady = new WeakMap<Custom, Promise<boolean>>();
+
+export const whenDatabaseRowReady = (model: Custom) => rowReady.get(model) || Promise.resolve(false);
+
+export const switchDatabaseRow = (model: Custom, data: TDatabaseRowData) => {
+ return rowSwitchers.get(model)?.(data) || Promise.resolve(false);
+};
export const newDatabaseRowModel = (options: {
app: App,
@@ -26,6 +37,9 @@ export const newDatabaseRowModel = (options: {
keywords?: string[],
focusPrimary?: boolean,
bindPrimary?: boolean,
+ navigation?: IDatabaseRowOpenData["navigation"],
+ boundBlockID?: string,
+ isDetached?: boolean,
},
}) => {
let customModel: Custom;
@@ -36,6 +50,9 @@ export const newDatabaseRowModel = (options: {
let unregisterRefresh: () => void;
let destroyed = false;
let renderVersion = 0;
+ let pendingRow: {data: TDatabaseRowData, resolve: (opened: boolean) => void};
+ let resolveReady: (ready: boolean) => void;
+ const ready = new Promise<boolean>(resolve => { resolveReady = resolve; });
const updateTitle = (custom: Custom, bodyElement: HTMLElement) => {
const primaryElement = bodyElement.querySelector<HTMLElement>('[data-primary="true"] [data-cell-value]');
if (!primaryElement?.dataset.cellValue) {
@@ -69,7 +86,8 @@ export const newDatabaseRowModel = (options: {
inheritDatabaseRowReadonly(contextProtyle, sourceProtyle);
sourceProtyle = undefined;
}
- const data = custom.data as typeof options.data;
+ const switching = pendingRow;
+ const data = switching?.data || custom.data as TDatabaseRowData;
const currentRenderVersion = ++renderVersion;
const bodyElement = document.createElement("div");
bodyElement.className = "custom-attr protyle-db-row__body";
@@ -78,15 +96,31 @@ export const newDatabaseRowModel = (options: {
return;
}
if (!element.querySelector(`[data-av-id="${data.avID}"]`)) {
+ if (switching) {
+ pendingRow = undefined;
+ switching.resolve(false);
+ return;
+ }
custom.tab.parent.removeTab(custom.tab.id);
+ resolveReady(false);
return;
}
// 保留当前内容,待属性和反链加载完成后一次替换,避免刷新期间出现空白。
- const restoreBindingRange = preserveAVBindingRange(contextProtyle, previousBodyElement);
+ const restoreBindingRange = switching ? undefined : preserveAVBindingRange(contextProtyle, previousBodyElement);
previousBodyElement.replaceWith(element);
- restoreBindingRange(element);
+ restoreBindingRange?.(element);
+ if (switching) {
+ custom.data = data;
+ pendingRow = undefined;
+ custom.element.querySelector(".protyle-content").scrollTop = 0;
+ }
updateLayout(custom);
updateTitle(custom, element);
+ resolveReady(true);
+ if (switching) {
+ saveLayout();
+ switching.resolve(true);
+ }
focusDatabasePrimary(custom.element, contextProtyle, data);
if (!data.keywords?.length) {
return;
@@ -157,11 +191,23 @@ export const newDatabaseRowModel = (options: {
});
custom.element.append(contextProtyle.highlight.styleElement, contextProtyle.hint.element);
render(custom);
+ const data = custom.data as TDatabaseRowData;
+ if (data.navigation) {
+ mountDesktopDatabaseRowNavigation(custom, {
+ ...data, databaseBlockID: data.blockID, notebookID: data.notebookId,
+ isDetached: data.isDetached !== false,
+ }, contextProtyle);
+ }
},
});
},
destroy() {
destroyed = true;
+ resolveReady(false);
+ pendingRow?.resolve(false);
+ pendingRow = undefined;
+ rowSwitchers.delete(customModel);
+ rowReady.delete(customModel);
resizeObserver?.disconnect();
unregisterRefresh?.();
ghostProtyle?.destroy();
@@ -173,5 +219,16 @@ export const newDatabaseRowModel = (options: {
updateLayout(customModel);
},
});
+ rowReady.set(model, ready);
+ rowSwitchers.set(model, data => {
+ if (destroyed || !contextProtyle || data.blockID !== model.data.blockID || data.avID !== model.data.avID) {
+ return Promise.resolve(false);
+ }
+ pendingRow?.resolve(false);
+ return new Promise(resolve => {
+ pendingRow = {data, resolve};
+ render(model);
+ });
+ });
return model;
};
diff --git a/app/src/editor/databaseRowSwitch.test.ts b/app/src/editor/databaseRowSwitch.test.ts
new file mode 100644
index 0000000000..88586ff9e8
--- /dev/null
+++ b/app/src/editor/databaseRowSwitch.test.ts
@@ -0,0 +1,179 @@
+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 "../protyle/render/av/openDatabaseRow";
+
+const {parse} = require("ifdef-loader/preprocessor");
+
+const createPreview = async (mobile: boolean) => {
+ const data: IDatabaseRowOpenData = {avID: "database", databaseBlockID: "carrier", notebookID: "notebook",
+ itemID: "first", valueID: "first-value", title: "First", isDetached: true,
+ navigation: {viewID: "view", query: ""}};
+ const title = {textContent: "", style: {}};
+ const content = {scrollTop: 25};
+ let body: Body;
+ class Body {
+ public isConnected = true;
+ public style = {};
+ public rowID = "";
+ public available = true;
+ public querySelector(selector: string) {
+ if (!this.available) { return null; }
+ return selector.includes("data-primary") ? {dataset: {
+ cellValue: encodeURIComponent(JSON.stringify({block: {content: this.rowID}})),
+ }} : {};
+ }
+ public replaceWith(next: Body) { this.isConnected = false; body = next; }
+ }
+ body = new Body();
+ const listeners = new Map<string, (event: {detail: unknown}) => void>();
+ const root = {
+ dataset: {}, clientWidth: 800, isConnected: true, scrollTop: 25,
+ querySelector: (selector: string): unknown => {
+ if (selector.includes("__body")) { return body; }
+ if (selector.includes("__title")) { return title; }
+ if (selector === ".protyle-content") { return content; }
+ return root;
+ },
+ append() {},
+ addEventListener: (name: string, listener: (event: {detail: unknown}) => void) => listeners.set(name, listener),
+ };
+ let closed = 0;
+ const tab = {updateTitle: (value: string) => { title.textContent = value; }, parent: {removeTab: () => { closed++; }}};
+ let destroy: () => void;
+ let loaded: () => void;
+ let refresh: () => void;
+ let navigate: (next: IDatabaseRowOpenData) => Promise<boolean>;
+ let mountedRow: string;
+ const requests: {element: Body, callback: (element: Body) => void}[] = [];
+ class Custom {
+ public data: Record<string, unknown>;
+ public element = root;
+ public tab = tab;
+ constructor(options: {data: Record<string, unknown>, init: (model: Custom) => void, destroy: () => void}) {
+ this.data = options.data;
+ destroy = options.destroy;
+ options.init(this);
+ }
+ }
+ const context = {id: "context", highlight: {}, hint: {}};
+ const modules: Record<string, unknown> = {
+ "../layout/dock/Custom": {Custom},
+ "../layout/util": {saveLayout() {}},
+ "../protyle/render/av/openDatabaseRow": {mountDesktopDatabaseRowNavigation: (_model: unknown, row: IDatabaseRowOpenData) => {
+ mountedRow = row.itemID;
+ }},
+ "../protyle/ui/padding": {getEditorHorizontalPadding: () => ({left: 0, right: 0})},
+ "../../../dialog": {Dialog: class {
+ public element = root;
+ constructor(options: {destroyCallback: () => void}) { destroy = options.destroyCallback; }
+ public destroy() { closed++; destroy(); }
+ }},
+ "./databaseRowNavigation": {
+ getDatabaseRowNavigation: (): undefined => undefined,
+ mountDatabaseRowNavigation: (_root: unknown, row: IDatabaseRowOpenData,
+ open: (next: IDatabaseRowOpenData) => Promise<boolean>) => {
+ mountedRow = row.itemID;
+ navigate = open;
+ },
+ },
+ };
+ const load = <T>(file: string) => {
+ const exports = {} as T;
+ runInNewContext(transpileModule(parse(readFileSync("src/" + file + ".ts", "utf8"),
+ {MOBILE: mobile, BROWSER: true}, false, true), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {
+ exports, document: {createElement: () => new Body()},
+ window: {siyuan: {dialogs: [], languages: {untitled: "Untitled"}, config: {editor: {databaseAttrShow: true}}}},
+ ResizeObserver: class { observe() {} disconnect() {} },
+ require: (name: string) => {
+ if (name === "../protyle" || name === "../../index") {
+ return {Protyle: class {
+ constructor(_app: unknown, _element: unknown, options: {after: (editor: unknown) => void}) {
+ loaded = () => options.after({protyle: context});
+ }
+ public destroy() {}
+ }};
+ }
+ if (name.endsWith("/blockAttr")) {
+ return {renderAVAttribute: (element: Body, id: string, _context: unknown,
+ callback: (element: Body) => void) => {
+ element.rowID = id;
+ requests.push({element, callback});
+ }};
+ }
+ if (name.endsWith("/databaseRowRefresh")) {
+ return {registerDatabaseRowRefresh: (_id: string, options: {refresh: () => void}) => {
+ refresh = options.refresh;
+ return () => {};
+ }};
+ }
+ if (name.endsWith("/binding")) { return {preserveAVBindingRange: () => () => {}}; }
+ if (name.endsWith("/rowReadonly")) { return {inheritDatabaseRowReadonly() {}}; }
+ if (name.endsWith("/primaryFocus")) { return {focusDatabasePrimary() {}}; }
+ return modules[name] || {};
+ },
+ });
+ return exports;
+ };
+ let model: Custom;
+ if (mobile) {
+ await load<typeof import("../protyle/render/av/openDatabaseRow")>("protyle/render/av/openDatabaseRow")
+ .openDatabaseRowByData({app: {}} as Pick<IProtyle, "app">, data);
+ } else {
+ const api = load<typeof import("./databaseRow")>("editor/databaseRow");
+ model = api.newDatabaseRowModel({app: {} as never, tab: tab as never,
+ data: {...data, blockID: data.databaseBlockID, notebookId: data.notebookID}}) as unknown as Custom;
+ navigate = next => api.switchDatabaseRow(model as never,
+ {...next, blockID: next.databaseBlockID, notebookId: next.notebookID});
+ }
+ loaded();
+ const complete = (index: number, available = true) => {
+ requests[index].element.available = available;
+ requests[index].callback(requests[index].element);
+ };
+ complete(0);
+ return {data, title, root, content, requests, complete, refresh: () => refresh(),
+ navigate: (next: IDatabaseRowOpenData) => navigate(next), destroy: () => destroy(),
+ body: () => body, closed: () => closed, savedRow: () => model?.data.itemID,
+ mountedRow: () => mountedRow};
+};
+
+for (const mobile of [false, true]) {
+ test(`row preview commits loaded content without clearing the current row (${mobile ? "mobile" : "desktop"})`, async () => {
+ const preview = await createPreview(mobile);
+ assert.equal(preview.mountedRow(), "first", "restoring the preview mounts its saved navigation");
+ const original = preview.body();
+ const next = {...preview.data, itemID: "second", valueID: "second-value", title: "Second"};
+ const switching = preview.navigate(next);
+ assert.equal(preview.body(), original);
+ assert.equal(preview.title.textContent, "first");
+ assert.equal(mobile ? preview.mountedRow() : preview.savedRow(), "first");
+ preview.refresh();
+ preview.complete(1);
+ assert.equal(preview.body(), original, "superseded response must not replace the current content");
+ preview.complete(2);
+ assert.equal(await switching, true);
+ assert.equal(preview.body().rowID, "second");
+ assert.equal(preview.title.textContent, "second");
+ assert.equal(mobile ? preview.mountedRow() : preview.savedRow(), "second");
+ assert.equal(mobile ? preview.root.scrollTop : preview.content.scrollTop, 0);
+ assert.equal(preview.closed(), 0);
+
+ const unavailable = preview.navigate({...next, itemID: "deleted"});
+ preview.complete(3, false);
+ assert.equal(await unavailable, false);
+ assert.equal(preview.body().rowID, "second");
+ assert.equal(preview.title.textContent, "second");
+ assert.equal(preview.closed(), 0);
+
+ const closing = preview.navigate({...next, itemID: "third"});
+ preview.destroy();
+ assert.equal(await closing, false);
+ preview.complete(4);
+ assert.equal(preview.body().rowID, "second");
+ });
+}
diff --git a/app/src/editor/index.ts b/app/src/editor/index.ts
index 2109e01078..6e5d000e7e 100644
--- a/app/src/editor/index.ts
+++ b/app/src/editor/index.ts
@@ -9,12 +9,14 @@ import {countBlockWord} from "../layout/status";
import type {App} from "../index";
import {fetchPost} from "../util/fetch";
import {Backlink} from "../layout/dock/Backlink";
+import type {IDatabaseRowOpenData} from "../protyle/render/av/openDatabaseRow";
export class Editor extends Model {
public element: HTMLElement;
public editor: Protyle;
public headElement: HTMLElement;
public backlink?: Backlink;
+ public databaseRow?: IDatabaseRowOpenData;
private backlinkElement?: HTMLElement;
private backlinkIntersectionObserver?: IntersectionObserver;
private backlinkMutationObserver?: MutationObserver;
diff --git a/app/src/editor/util.ts b/app/src/editor/util.ts
index c12b4c0f02..e1f4a4f44e 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
}
};
-export const newTab = (options: IOpenFileOptions) => {
+export const newTab = (options: IOpenFileOptions, afterInitProtyle?: ConstructorParameters<typeof Editor>[0]["afterInitProtyle"]) => {
let tab: Tab;
if (options.assetPath) {
const suffix = getAssetExtension(options.assetPath).toLowerCase();
@@ -649,7 +649,9 @@ export const newTab = (options: IOpenFileOptions) => {
data: options.custom.data
}));
}
- setPanelFocus(tab.panelElement.parentElement.parentElement);
+ if (!options.keepCursor) {
+ setPanelFocus(tab.panelElement.parentElement.parentElement);
+ }
}
});
} else if (options.searchData) {
@@ -678,8 +680,10 @@ export const newTab = (options: IOpenFileOptions) => {
blockId: options.id,
rootId: options.rootID,
notebookId: options.notebookId,
- action: [Constants.CB_GET_ALL, isPhablet() ? Constants.CB_GET_HL : Constants.CB_GET_FOCUS],
+ action: options.keepCursor ? [Constants.CB_GET_ALL] :
+ [Constants.CB_GET_ALL, isPhablet() ? Constants.CB_GET_HL : Constants.CB_GET_FOCUS],
scrollPosition: options.scrollPosition,
+ afterInitProtyle,
});
} else {
editor = new Editor({
@@ -691,6 +695,7 @@ export const newTab = (options: IOpenFileOptions) => {
mode: options.mode,
action: options.action,
scrollPosition: options.scrollPosition,
+ afterInitProtyle,
});
}
tab.addModel(editor);
diff --git a/app/src/layout/databaseRowRestore.test.ts b/app/src/layout/databaseRowRestore.test.ts
new file mode 100644
index 0000000000..a3cea475b5
--- /dev/null
+++ b/app/src/layout/databaseRowRestore.test.ts
@@ -0,0 +1,56 @@
+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 "../protyle/render/av/openDatabaseRow";
+
+const {parse} = require("ifdef-loader/preprocessor");
+
+test("bound row layout restores navigation with its source view and current item", () => {
+ let initialize: () => void;
+ let restored: IDatabaseRowOpenData;
+ class Editor {
+ public databaseRow?: IDatabaseRowOpenData;
+ public editor = {protyle: {notebookId: "target-notebook", block: {id: "bound", rootID: "document", showAll: true},
+ preview: {element: {classList: {contains: () => true}}},
+ element: {dataset: {databaseRowId: "bound"}}}};
+ constructor(options?: {afterInitProtyle: (editor: Editor["editor"]) => void}) {
+ if (options) { initialize = () => options.afterInitProtyle(this.editor); }
+ }
+ }
+ class UnusedModel {}
+ const modules: Record<string, unknown> = {
+ "../editor": {Editor},
+ "../constants": {Constants: {CB_GET_ALL: "all", CB_GET_SCROLL: "scroll", CB_GET_FOCUS: "focus"}},
+ "../util/functions": {isWindow: () => false},
+ "../util/pathName": {isEncryptedBox: (id: string) => id === "encrypted-notebook"},
+ "../protyle/util/compatibility": {isPhablet: () => false},
+ "../protyle/render/av/openDatabaseRow": {
+ showDatabaseRowPreview: (model: Editor, data: IDatabaseRowOpenData) => {
+ assert.equal(model.databaseRow, data);
+ restored = data;
+ },
+ },
+ };
+ const exports = {} as typeof import("./util");
+ runInNewContext(transpileModule(parse(readFileSync("src/layout/util.ts", "utf8"),
+ {MOBILE: false, BROWSER: true}, false, true), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {exports, window: {}, require: (name: string) => modules[name] ||
+ new Proxy({}, {get: () => UnusedModel})});
+ const model = new Editor();
+ model.databaseRow = {avID: "database", databaseBlockID: "carrier", notebookID: "source-notebook",
+ itemID: "third", valueID: "third-value", boundBlockID: "bound", title: "", isDetached: false,
+ navigation: {viewID: "view", query: "search", groupID: "group"}};
+ const json: ILayoutJSON = {};
+ exports.layoutToJSON(model as never, json);
+ const persisted = JSON.parse(JSON.stringify(json));
+ const reopened = exports.newModelByInitData({} as never, {} as never, persisted) as unknown as Editor;
+ initialize();
+ assert.deepEqual(restored, model.databaseRow);
+ assert.equal(reopened.editor.protyle.element.dataset.databaseRowId, "bound");
+ assert.equal(exports.isSensitiveTab({model} as never), false);
+ model.databaseRow.notebookID = "encrypted-notebook";
+ assert.equal(exports.isSensitiveTab({model} as never), true, "source database context must not leak into a plaintext layout");
+});
diff --git a/app/src/layout/util.ts b/app/src/layout/util.ts
index d57a5dfe58..adb5eed825 100644
--- a/app/src/layout/util.ts
+++ b/app/src/layout/util.ts
@@ -29,6 +29,7 @@ import {isEncryptedBox, parseUriInfo} from "../util/pathName";
import {Custom} from "./dock/Custom";
import {newCardModel} from "../card/newCardTab";
import {newDatabaseRowModel} from "../editor/databaseRow";
+import {showDatabaseRowPreview} from "../protyle/render/av/openDatabaseRow";
import type {App} from "../index";
import {afterLayoutReady} from "../plugin/loader";
import {newCenterEmptyTab, resizeTabs, setTabPosition} from "./tabUtil";
@@ -54,7 +55,8 @@ const isBuiltInCustomModel = (type: string) => {
export const isSensitiveTab = (tab: Tab) => {
if (tab.model instanceof Editor) {
- return isEncryptedBox(tab.model.editor.protyle.notebookId);
+ return isEncryptedBox(tab.model.editor.protyle.notebookId) ||
+ isEncryptedBox(tab.model.databaseRow?.notebookID);
}
if (tab.model instanceof Search) {
return isSensitiveSearchConfig(tab.model.config);
@@ -821,6 +823,7 @@ export const layoutToJSON = (layout: Layout | Wnd | Tab | Model, json: any, brea
json.mode = layout.editor.protyle.preview.element.classList.contains("fn__none") ? "wysiwyg" : "preview";
json.action = (layout.editor.protyle.block.showAll && layout.editor.protyle.block.id !== layout.editor.protyle.block.rootID) ? Constants.CB_GET_ALL : Constants.CB_GET_SCROLL;
json.databaseRowId = layout.editor.protyle.element.dataset.databaseRowId;
+ json.databaseRow = layout.databaseRow;
json.instance = "Editor";
if (isWindow()) {
const scrollAttr = saveScroll(layout.editor.protyle, true);
@@ -1037,7 +1040,9 @@ export const newModelByInitData = (app: App, tab: Tab, json: any) => {
scrollAttr: json.scrollAttr,
action,
afterInitProtyle(editor) {
- if (json.databaseRowId) {
+ if (json.databaseRow?.navigation) {
+ showDatabaseRowPreview(editorModel, json.databaseRow, editor.protyle);
+ } else if (json.databaseRowId) {
editor.protyle.databaseAttributePanel?.expand();
editor.protyle.contentElement.scrollTop = 0;
}
@@ -1046,6 +1051,7 @@ export const newModelByInitData = (app: App, tab: Tab, json: any) => {
if (json.databaseRowId) {
editorModel.editor.protyle.element.dataset.databaseRowId = json.databaseRowId;
}
+ editorModel.databaseRow = json.databaseRow;
model = editorModel;
}
return model;
diff --git a/app/src/protyle/render/av/databaseRowPreviewNavigation.test.ts b/app/src/protyle/render/av/databaseRowPreviewNavigation.test.ts
index 07d2ab1662..3bc095f628 100644
--- a/app/src/protyle/render/av/databaseRowPreviewNavigation.test.ts
+++ b/app/src/protyle/render/av/databaseRowPreviewNavigation.test.ts
@@ -13,8 +13,17 @@ test("row navigation replaces only its original desktop preview across bound and
const created: IOpenFileOptions[] = [];
const app = {};
let request: (response: unknown) => void;
+ let switched: (opened: boolean) => void;
+ let documentLoaded: () => void;
+ let attributesLoaded: (element: unknown) => void;
+ let customLoaded: (ready: boolean) => void;
+ let checkSource: () => void;
const element = () => {
- const root = {isConnected: true, dataset: {}, querySelector: (): unknown => root, dispatchEvent() {}};
+ const classes = new Set<string>();
+ const root = {isConnected: true, dataset: {}, querySelector: (): unknown => root, dispatchEvent() {},
+ remove() { root.isConnected = false; },
+ classList: {add: (name: string) => classes.add(name), remove: (name: string) => classes.delete(name),
+ contains: (name: string) => classes.has(name)}};
return root;
};
interface TestWnd {
@@ -26,6 +35,7 @@ test("row navigation replaces only its original desktop preview across bound and
parent: TestWnd;
model: Custom | Editor;
panelElement: ReturnType<typeof element>;
+ callback?: (tab: TestTab) => void;
}
const wnd: TestWnd = {
addTab(tab: ReturnType<typeof makeTab>, _keep: boolean, _save: boolean, _active: string, replace: string) {
@@ -40,15 +50,20 @@ test("row navigation replaces only its original desktop preview across bound and
public data = {};
public parent: ReturnType<typeof makeTab>;
public update() {}
+ public resize() {}
+ public destroy() {}
+ public send() {}
}
class Editor {
public app = app;
public parent: ReturnType<typeof makeTab>;
- public editor = {protyle: {element: element(), contentElement: {scrollTop: 20}, upload: {isUploading: false},
- databaseAttributePanel: {expand() {}, afterRender() {}}}};
+ public editor = {resize() {}, protyle: {element: element(), contentElement: {scrollTop: 20}, upload: {isUploading: false},
+ databaseAttributePanel: {expand() {}, afterRender(callback: (element: unknown) => void) { attributesLoaded = callback; }}}};
+ public destroy() {}
+ public send() {}
}
const makeTab = (id: string, model: Custom | Editor): TestTab => {
- const tab = {id, parent: wnd, model, panelElement: element()};
+ const tab = {id, parent: wnd, model, panelElement: element(), callback() {}};
model.parent = tab;
return tab;
};
@@ -57,9 +72,17 @@ test("row navigation replaces only its original desktop preview across bound and
let latest: ReturnType<typeof makeTab>;
const modules: Record<string, unknown> = {
"../../../layout/dock/Custom": {Custom}, "../../../editor": {Editor},
+ "../../../editor/databaseRow": {whenDatabaseRowReady: () => new Promise(resolve => { customLoaded = resolve; }),
+ switchDatabaseRow: (model: Custom, row: IDatabaseRowOpenData) => {
+ assert.equal(model, initial);
+ assert.equal(row.itemID, "next-detached");
+ return new Promise(resolve => { switched = resolve; });
+ }},
"../../../editor/util": {
+ updatePanelByEditor() {},
openFile: async (options: IOpenFileOptions) => { options.afterOpen(initial as never); return initial.parent; },
- newTab: (options: IOpenFileOptions) => {
+ newTab: (options: IOpenFileOptions, afterInit: () => void) => {
+ documentLoaded = afterInit;
created.push(options);
latest = makeTab("new-" + created.length, options.custom ? new Custom() : new Editor());
return latest;
@@ -67,6 +90,7 @@ test("row navigation replaces only its original desktop preview across bound and
},
"../../../util/fetch": {fetchSyncPost: () => new Promise(resolve => { request = resolve; })},
"../../../dialog/message": {showMessage() {}},
+ "../../../layout/util": {saveLayout() {}},
"./rowReadonly": {inheritDatabaseRowReadonly() {}},
"./databaseRowNavigation": {
getDatabaseRowNavigation: (): undefined => undefined,
@@ -78,38 +102,79 @@ test("row navigation replaces only its original desktop preview across bound and
{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"}}},
+ window: {setTimeout, clearTimeout, siyuan: {config: {editor: {databaseAttrShow: true}}, languages: {untitled: "Untitled"}}},
+ document: {body: {append() {}}},
+ MutationObserver: class {
+ constructor(callback: () => void) { checkSource = callback; }
+ public observe() {}
+ public disconnect() {}
+ },
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 reuse = callbacks.get(initial.element)({...data, itemID: "next-detached"});
+ assert.equal(created.length, 0);
+ assert.equal(removed.length, 0);
+ switched(true);
+ assert.equal(await reuse, true);
+ assert.equal(created.length, 0);
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"}});
+ await new Promise(setImmediate);
+ assert.equal(removed.length, 0, "the current preview stays until document and attributes load");
+ assert.equal(latest.panelElement.classList.contains("fn__none"), true);
+ documentLoaded();
+ await new Promise(setImmediate);
+ assert.equal(removed.length, 0);
+ attributesLoaded({querySelector: () => ({})});
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;
+ let 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);
+ const toBound = callbacks.get(bound.editor.protyle.element)({...data, isDetached: false, boundBlockID: "next-bound"});
+ request({code: 0, data: {rootID: "next-document", rootTitle: "Next"}});
+ await new Promise(setImmediate);
+ assert.deepEqual(removed, ["initial"]);
+ documentLoaded();
+ await new Promise(setImmediate);
+ assert.deepEqual(removed, ["initial"]);
+ attributesLoaded({querySelector: () => ({})});
+ assert.equal(await toBound, true);
+ bound = latest.model as Editor;
+ const toDetached = callbacks.get(bound.editor.protyle.element)(data);
assert.deepEqual(removed, ["initial", "new-1"]);
- assert.equal(created[1].custom.data.itemID, "row");
- assert.equal(created[1].custom.data.navigation.viewID, "view");
+ customLoaded(true);
+ assert.equal(await toDetached, true);
+ assert.deepEqual(removed, ["initial", "new-1", "new-2"]);
+ assert.equal(created[2].custom.data.itemID, "row");
+ assert.equal(created[2].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);
+ assert.equal(removed.length, 3);
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);
+ assert.equal(created.length, 3);
+ latest.panelElement.isConnected = true;
+ const cancelled = callbacks.get(detached.element)({...data, isDetached: false, boundBlockID: "bound"});
+ request({code: 0, data: {rootID: "document"}});
+ await new Promise(setImmediate);
+ detached.parent.panelElement.isConnected = false;
+ checkSource();
+ assert.equal(await cancelled, false);
+ assert.equal(latest.panelElement.isConnected, false, "cancelled preview is removed from its staging container");
+ assert.equal(removed.length, 3);
});
diff --git a/app/src/protyle/render/av/openDatabaseRow.ts b/app/src/protyle/render/av/openDatabaseRow.ts
index 59a3d7ab88..129cd31f58 100644
--- a/app/src/protyle/render/av/openDatabaseRow.ts
+++ b/app/src/protyle/render/av/openDatabaseRow.ts
@@ -5,13 +5,15 @@ import {Dialog} from "../../../dialog";
import {renderAVAttribute} from "./blockAttr";
import {Protyle} from "../../index";
/// #else
-import {newTab, openFile, openFileById} from "../../../editor/util";
+import {newTab, openFile, openFileById, updatePanelByEditor} 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";
+import {switchDatabaseRow, whenDatabaseRowReady} from "../../../editor/databaseRow";
+import {saveLayout} from "../../../layout/util";
/// #endif
import {searchMarkRender} from "../searchMarkRender";
import {registerDatabaseRowRefresh} from "./databaseRowRefresh";
@@ -67,6 +69,9 @@ const openMobileDatabaseRow = (protyle: Pick<IProtyle, "app">, data: IDatabaseRo
const context: { ghostProtyle?: Protyle } = {};
let unregisterRefresh: () => void;
let renderVersion = 0;
+ let destroyed = false;
+ let contextProtyle: IProtyle;
+ let pendingRow: {data: IDatabaseRowOpenData, resolve: (opened: boolean) => void};
const dialog = new Dialog({
content: `<div class="protyle-db-row protyle-db-row--mobile protyle-content">
<div class="protyle-db-row__title"><svg><use xlink:href="#iconDatabase"></use></svg><span></span></div>
@@ -77,13 +82,29 @@ const openMobileDatabaseRow = (protyle: Pick<IProtyle, "app">, data: IDatabaseRo
containerClassName: "b3-dialog__container--database-row",
disableAnimation: true,
destroyCallback() {
+ destroyed = true;
renderVersion++;
+ pendingRow?.resolve(false);
+ pendingRow = undefined;
unregisterRefresh?.();
context.ghostProtyle?.destroy();
},
});
const rowElement = dialog.element.querySelector<HTMLElement>(".protyle-db-row");
- mountDatabaseRowNavigation(rowElement, data, next => openDatabaseRowByData(protyle, next));
+ const mountNavigation = () => mountDatabaseRowNavigation(rowElement, data, next => {
+ if (!next.isDetached && window.siyuan.config.editor.databaseAttrShow) {
+ return openDatabaseRowByData(protyle, next);
+ }
+ if (!contextProtyle || !rowElement.isConnected) {
+ return Promise.resolve(false);
+ }
+ pendingRow?.resolve(false);
+ return new Promise<boolean>(resolve => {
+ pendingRow = {data: next, resolve};
+ render(contextProtyle);
+ });
+ });
+ mountNavigation();
rowElement.querySelector(".protyle-db-row__title span").textContent = title;
const render = (contextProtyle: IProtyle) => {
const previousBodyElement = rowElement.querySelector<HTMLElement>(".protyle-db-row__body");
@@ -91,20 +112,35 @@ const openMobileDatabaseRow = (protyle: Pick<IProtyle, "app">, data: IDatabaseRo
return;
}
const currentRenderVersion = ++renderVersion;
+ const switching = pendingRow;
+ const renderData = switching?.data || data;
const bodyElement = document.createElement("div");
bodyElement.className = "custom-attr protyle-db-row__body";
- renderAVAttribute(bodyElement, data.itemID, contextProtyle, (element) => {
+ renderAVAttribute(bodyElement, renderData.itemID, contextProtyle, (element) => {
if (currentRenderVersion !== renderVersion || !previousBodyElement.isConnected) {
return;
}
- if (!element.querySelector(`[data-av-id="${data.avID}"]`)) {
+ if (!element.querySelector(`[data-av-id="${renderData.avID}"]`)) {
+ if (switching) {
+ pendingRow = undefined;
+ switching.resolve(false);
+ return;
+ }
dialog.destroy();
return;
}
// 保留当前内容,待属性和反链加载完成后一次替换,避免刷新期间出现空白。
- const restoreBindingRange = preserveAVBindingRange(contextProtyle, previousBodyElement);
+ const restoreBindingRange = switching ? undefined : preserveAVBindingRange(contextProtyle, previousBodyElement);
previousBodyElement.replaceWith(element);
- restoreBindingRange(element);
+ restoreBindingRange?.(element);
+ if (switching) {
+ data = renderData;
+ pendingRow = undefined;
+ rowElement.scrollTop = 0;
+ rowElement.querySelector(".protyle-db-row__title span").textContent = data.title || window.siyuan.languages.untitled;
+ mountNavigation();
+ switching.resolve(true);
+ }
const primaryElement = element.querySelector<HTMLElement>('[data-primary="true"] [data-cell-value]');
if (primaryElement?.dataset.cellValue) {
const value = JSON.parse(decodeURIComponent(primaryElement.dataset.cellValue)) as IAVCellValue;
@@ -115,17 +151,20 @@ const openMobileDatabaseRow = (protyle: Pick<IProtyle, "app">, data: IDatabaseRo
highlightDatabaseRow(contextProtyle, rowElement, data);
focusDatabasePrimary(rowElement, contextProtyle, data);
}, {
- avID: data.avID,
- itemID: data.itemID,
- valueID: data.valueID,
- databaseBlockID: data.databaseBlockID,
+ avID: renderData.avID,
+ itemID: renderData.itemID,
+ valueID: renderData.valueID,
+ databaseBlockID: renderData.databaseBlockID,
});
};
context.ghostProtyle = new Protyle(protyle.app, document.createElement("div"), {
blockId: data.databaseBlockID,
notebookId: data.notebookID,
after(editor) {
- const contextProtyle = editor.protyle;
+ if (destroyed) {
+ return;
+ }
+ contextProtyle = editor.protyle;
inheritDatabaseRowReadonly(contextProtyle, protyle);
rowElement.dataset.protyleId = contextProtyle.id;
unregisterRefresh = registerDatabaseRowRefresh(contextProtyle.id, {
@@ -138,11 +177,16 @@ const openMobileDatabaseRow = (protyle: Pick<IProtyle, "app">, data: IDatabaseRo
});
};
/// #else
-const showDatabaseRowPreview = (model: Editor, data: IDatabaseRowOpenData, source: Partial<IProtyle>) => {
+export const showDatabaseRowPreview = (model: Editor, data: IDatabaseRowOpenData, source: Partial<IProtyle>) => {
if (!model?.editor?.protyle) {
return;
}
const editorProtyle = model.editor.protyle;
+ model.databaseRow = {
+ avID: data.avID, databaseBlockID: data.databaseBlockID, notebookID: data.notebookID,
+ itemID: data.itemID, valueID: data.valueID, boundBlockID: data.boundBlockID,
+ title: "", isDetached: data.isDetached, navigation: data.navigation,
+ };
inheritDatabaseRowReadonly(editorProtyle, source);
editorProtyle.element.dataset.databaseRowId = data.boundBlockID || "";
mountDesktopDatabaseRowNavigation(model, data, source);
@@ -152,6 +196,7 @@ const showDatabaseRowPreview = (model: Editor, data: IDatabaseRowOpenData, sourc
highlightDatabaseRow(editorProtyle, editorProtyle.contentElement, data);
focusDatabasePrimary(editorProtyle.contentElement, editorProtyle, data);
});
+ saveLayout();
};
const focusDatabaseRowPreview = (model: Editor, data: IDatabaseRowOpenData, source: Partial<IProtyle>) => {
@@ -194,7 +239,7 @@ const getCustomRowData = (data: IDatabaseRowOpenData) => ({
...data, blockID: data.databaseBlockID, notebookId: data.notebookID,
});
-const mountDesktopDatabaseRowNavigation = (model: Editor | Custom, data: IDatabaseRowOpenData,
+export 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 => {
@@ -202,6 +247,13 @@ const mountDesktopDatabaseRowNavigation = (model: Editor | Custom, data: IDataba
const wnd = tab.parent;
const options: IOpenFileOptions = {app: model.app};
if (next.isDetached || !window.siyuan.config.editor.databaseAttrShow) {
+ if (model instanceof Custom) {
+ const opened = await switchDatabaseRow(model, getCustomRowData(next));
+ if (opened) {
+ mountDesktopDatabaseRowNavigation(model, next, source);
+ }
+ return opened;
+ }
options.custom = {id: "siyuan-database-row", icon: "iconDatabase",
title: next.title || window.siyuan.languages.untitled, data: getCustomRowData(next)};
} else {
@@ -220,15 +272,79 @@ const mountDesktopDatabaseRowNavigation = (model: Editor | Custom, data: IDataba
showMessage(window.siyuan.languages.uploading);
return false;
}
- const opened = newTab(options);
+ let documentLoaded: () => void;
+ const loaded = new Promise<void>(resolve => { documentLoaded = resolve; });
+ const opened = newTab({...options, keepCursor: true}, () => documentLoaded());
+ opened.parent = wnd;
+ opened.panelElement.classList.add("fn__none");
+ document.body.append(opened.panelElement);
+ let preparing = true;
+ let cancel: () => void;
+ const cancelled = new Promise<boolean>(resolve => { cancel = () => resolve(false); });
+ const observer = new MutationObserver(() => {
+ if (!tab.panelElement.isConnected || tab.model !== model || tab.parent !== wnd) {
+ cancel();
+ }
+ });
+ observer.observe(document.body, {childList: true, subtree: true});
+ const timeout = window.setTimeout(cancel, 60000);
+ let ready = false;
+ try {
+ // 在布局之外加载目标预览,正文和属性就绪前保留当前页签及其内容。
+ opened.callback(opened);
+ opened.callback = undefined;
+ ready = await Promise.race([cancelled, (async () => {
+ if (opened.model instanceof Custom) {
+ opened.model.element.dispatchEvent(new CustomEvent("database-row-readonly", {detail: source}));
+ opened.model.update();
+ return whenDatabaseRowReady(opened.model);
+ }
+ await loaded;
+ if (!preparing || !(opened.model instanceof Editor)) {
+ return false;
+ }
+ const protyle = opened.model.editor.protyle;
+ inheritDatabaseRowReadonly(protyle, source);
+ protyle.databaseAttributePanel?.expand(next.avID);
+ return new Promise<boolean>(resolve => {
+ if (!protyle.databaseAttributePanel) {
+ resolve(false);
+ return;
+ }
+ protyle.databaseAttributePanel.afterRender(element => {
+ resolve(!!element.querySelector(`[data-av-id="${next.avID}"]`));
+ });
+ });
+ })()]);
+ ready = ready && tab.panelElement.isConnected && tab.model === model && tab.parent === wnd;
+ if (model instanceof Editor && model.editor.protyle.upload.isUploading) {
+ ready = false;
+ showMessage(window.siyuan.languages.uploading);
+ }
+ } finally {
+ preparing = false;
+ observer.disconnect();
+ window.clearTimeout(timeout);
+ if (!ready) {
+ opened.model?.destroy();
+ opened.model?.send("closews", {});
+ opened.panelElement.remove();
+ }
+ }
+ if (!ready) {
+ return false;
+ }
+ opened.panelElement.classList.remove("fn__none");
// 复用来源预览所在的分屏,不依赖异步请求完成时用户正激活哪个分屏。
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();
+ opened.model.resize();
mountDesktopDatabaseRowNavigation(opened.model, next, source);
} else if (opened.model instanceof Editor) {
+ opened.model.editor.resize();
showDatabaseRowPreview(opened.model, next, source);
+ updatePanelByEditor({protyle: opened.model.editor.protyle,
+ focus: false, pushBackStack: false, reload: false, resize: false});
}
return true;
}, model instanceof Custom ? undefined : model.editor.protyle.breadcrumb?.element.parentElement);
@@ -281,19 +397,7 @@ export const openDatabaseRowByData = async (protyle: Pick<IProtyle, "app">, data
id: "siyuan-database-row",
icon: "iconDatabase",
title,
- data: {
- avID: data.avID,
- blockID: data.databaseBlockID,
- notebookId: data.notebookID,
- itemID: data.itemID,
- valueID: data.valueID,
- title,
- matchedValueID: data.matchedValueID,
- matchedKeyID: data.matchedKeyID,
- keywords: data.keywords,
- focusPrimary: data.focusPrimary,
- bindPrimary: data.bindPrimary,
- },
+ data: getCustomRowData(data),
},
afterOpen(model) {
if (model instanceof Custom) {
@@ -301,6 +405,7 @@ export const openDatabaseRowByData = async (protyle: Pick<IProtyle, "app">, data
model.element.dispatchEvent(new CustomEvent("database-row-readonly", {detail: protyle}));
model.update();
mountDesktopDatabaseRowNavigation(model, data, protyle);
+ saveLayout();
}
},
});
diff --git a/app/src/protyle/render/av/rowReadonly.test.ts b/app/src/protyle/render/av/rowReadonly.test.ts
index 5e0d60af9e..ebf22d9a80 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})},
+ "../../../layout/util": {saveLayout() {}},
"./databaseRowNavigation": {getDatabaseRowNavigation: (): undefined => undefined, mountDatabaseRowNavigation() {}},
};
const load = <T>(file: string) => {
diff --git a/app/src/protyle/util/compatibility.ts b/app/src/protyle/util/compatibility.ts
index 935a1273c6..6f4e6371d6 100644
--- a/app/src/protyle/util/compatibility.ts
+++ b/app/src/protyle/util/compatibility.ts
@@ -897,12 +897,13 @@ export const isSensitiveLayoutData = (data?: {
type?: string,
notebookId?: string,
config?: Config.IUILayoutTabSearchConfig,
+ databaseRow?: {notebookID: string},
}) => {
if (!data) {
return false;
}
if (data.instance === "Editor") {
- return isEncryptedBox(data.notebookId);
+ return isEncryptedBox(data.notebookId) || isEncryptedBox(data.databaseRow?.notebookID);
}
if (data.instance === "Search") {
return isSensitiveSearchConfig(data.config);
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 707044ea6b..fc425996cf 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -2500,6 +2500,7 @@ declare namespace Config {
* 数据库行预览块 ID
*/
databaseRowId?: string;
+ databaseRow?: import("../protyle/render/av/openDatabaseRow").IDatabaseRowOpenData;
/**
* Object name
*/
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 013ef90da1..00783d3086 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -755,6 +755,7 @@ interface ILayoutJSON extends ILayoutOptions {
icon?: string
rootId?: string
databaseRowId?: string
+ databaseRow?: import("../protyle/render/av/openDatabaseRow").IDatabaseRowOpenData
active?: boolean
pin?: boolean
isPreview?: boolean