Skip to content

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

:art: Smooth back and forward navigation in the current tab https://github.com/siyuan-note/siyuan/issues/19764

Daniel27f2ab3dc7ad
diff --git a/app/src/editor/navigationHistory.test.ts b/app/src/editor/navigationHistory.test.ts
index ebf206e3c6..8aa0edcde7 100644
--- a/app/src/editor/navigationHistory.test.ts
+++ b/app/src/editor/navigationHistory.test.ts
@@ -113,3 +113,109 @@ test("tablet tab switches navigate A B C backward and forward without touching t
await context.forward({});
assert.deepEqual(visited, ["B", "A", "B", "C"]);
});
+
+const restoreClosedHistoryEntry = async (disabled: boolean) => {
+ const historySource = createSourceFile("backForward.ts", readFileSync("src/util/backForward.ts", "utf8"), ScriptTarget.ES2021, true);
+ const declaration = historySource.statements.find(statement => isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(item => item.name.getText(historySource) === "focusStack"));
+ const calls: string[] = [];
+ const oldElement = {};
+ const newElement = {};
+ const protyle = {element: newElement, block: {rootID: "A"}, disabled, title: {editElement: {}}};
+ let afterInit: () => void;
+ let editorOptions: any;
+ class ActiveElement {
+ blur() { calls.push("blur"); }
+ }
+ const previewTab = (id: string, focused: boolean) => ({
+ id,
+ headElement: {classList: {contains: (name: string) =>
+ name === "item--unupdate" || (name === "item--focus" && focused)}},
+ });
+ const wnd = {
+ children: [previewTab("current", true), previewTab("other", false)],
+ addTab(tab: any) { tab.callback(tab); },
+ removeTab(id: string, batch: boolean, animate: boolean) { calls.push(`remove:${id}:${batch}:${animate}`); },
+ showHeading() {},
+ };
+ const context: any = {
+ window: {siyuan: {
+ config: {fileTree: {openFilesUseCurrentTab: true}},
+ layout: {}, storage: {positions: {}}, backStack: [],
+ }},
+ document: {
+ activeElement: new ActiveElement(),
+ contains: (element: unknown) => element === newElement,
+ querySelector: () => ({getAttribute: () => "wnd"}),
+ },
+ HTMLElement: ActiveElement,
+ Constants: {LOCAL_FILEPOSITION: "positions", CB_GET_SCROLL: "scroll", CB_GET_ALL: "all", CB_GET_UNUNDO: "unundo"},
+ hideElements: () => {},
+ fetchSyncPost: async (path: string) => path.endsWith("checkBlockExist") ?
+ {code: 0, data: true} : {code: 0, data: {rootID: "A", rootTitle: "A", rootIcon: ""}},
+ getInstanceById: () => wnd,
+ isEncryptedBox: () => false,
+ isPhablet: () => false,
+ saveScroll: (): undefined => undefined,
+ forwardStack: [],
+ focusByOffset: () => calls.push("focus"),
+ Tab: class {
+ callback: (tab: any) => void;
+ headElement = {classList: {contains: (name: string) => name === "item--focus"}};
+ model: any;
+ constructor(options: any) { this.callback = options.callback; }
+ addModel(model: any) { this.model = model; }
+ },
+ Editor: class {
+ editor = {protyle};
+ constructor(options: any) {
+ editorOptions = options;
+ afterInit = () => options.afterInitProtyle(this.editor);
+ }
+ },
+ };
+ runInNewContext(transpileModule(declaration.getText(historySource).replace(/^export /, "") +
+ "\nglobalThis.restore = focusStack;", {compilerOptions: {target: ScriptTarget.ES2021}}).outputText, context);
+ const stack = {id: "A", position: {start: 2, end: 2}, protyle: {element: oldElement, block: {rootID: "A"}, notebookId: "notebook"}};
+ assert.equal(await context.restore({}, stack), true);
+ return {calls, protyle, editorOptions, afterInit};
+};
+
+test("history restores a closed document through the focused preview tab without early focus", async () => {
+ const {calls, editorOptions, afterInit} = await restoreClosedHistoryEntry(false);
+ assert.deepEqual(calls, ["blur", "remove:current:false:false"]);
+ assert.equal(editorOptions.notebookId, "notebook");
+ assert.deepEqual(Array.from(editorOptions.action), ["scroll", "unundo"]);
+ afterInit();
+ assert.deepEqual(calls, ["blur", "remove:current:false:false", "focus"]);
+});
+
+test("history does not focus a read-only document after it loads", async () => {
+ const {calls, afterInit} = await restoreClosedHistoryEntry(true);
+ afterInit();
+ assert.deepEqual(calls, ["blur", "remove:current:false:false"]);
+});
+
+test("history switches to an open read-only tab without focusing its editor", async () => {
+ const historySource = createSourceFile("backForward.ts", readFileSync("src/util/backForward.ts", "utf8"), ScriptTarget.ES2021, true);
+ const declaration = historySource.statements.find(statement => isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(item => item.name.getText(historySource) === "focusStack"));
+ const calls: unknown[][] = [];
+ const protyle = {
+ element: {}, block: {rootID: "A", showAll: false}, toolbar: {range: undefined as Range | undefined}, disabled: true,
+ title: {editElement: {getBoundingClientRect: () => ({height: 0})}},
+ model: {parent: {headElement: {}, parent: {switchTab: (...args: unknown[]) => calls.push(args)}}},
+ };
+ const context: any = {
+ document: {contains: () => true},
+ hideElements: () => {},
+ isPhablet: () => false,
+ readingPositions: new WeakMap(),
+ focusByOffset: () => calls.push(["focus"]),
+ };
+ runInNewContext(transpileModule(declaration.getText(historySource).replace(/^export /, "") +
+ "\nglobalThis.restore = focusStack;", {compilerOptions: {target: ScriptTarget.ES2021}}).outputText, context);
+ assert.equal(await context.restore({}, {id: "A", position: {start: 0, end: 0}, protyle}), true);
+ assert.deepEqual(Array.from(calls[0]), [{}, false, true, true, true, false]);
+ assert.equal(calls.length, 1);
+});
diff --git a/app/src/layout/Wnd.ts b/app/src/layout/Wnd.ts
index 44f21cf35c..b141d81f41 100644
--- a/app/src/layout/Wnd.ts
+++ b/app/src/layout/Wnd.ts
@@ -666,7 +666,8 @@ export class Wnd {
}
}
- public switchTab(target: HTMLElement, pushBack = false, update = true, resize = true, isSaveLayout = true) {
+ public switchTab(target: HTMLElement, pushBack = false, update = true, resize = true, isSaveLayout = true,
+ focusEditor = !isPhablet()) {
let currentTab: Tab;
let isInitActive = false;
this.children.forEach((item) => {
@@ -762,7 +763,7 @@ export class Wnd {
if (update) {
updatePanelByEditor({
protyle: currentTab.model.editor.protyle,
- focus: !isPhablet(),
+ focus: focusEditor,
pushBackStack: pushBack,
reload: false,
resize,
diff --git a/app/src/util/backForward.ts b/app/src/util/backForward.ts
index 2f6b97e696..426dd7f0a7 100644
--- a/app/src/util/backForward.ts
+++ b/app/src/util/backForward.ts
@@ -71,11 +71,14 @@ const focusStack = async (app: App, stack: IBackStack) => {
if (info.code !== 0) {
return;
}
+ if (document.activeElement instanceof HTMLElement) {
+ document.activeElement.blur();
+ }
const tab = new Tab({
title: info.data.rootTitle,
docIcon: info.data.rootIcon,
callback(tab) {
- const scrollAttr = saveScroll(stack.protyle, true) as IScrollAttr;
+ const scrollAttr = (saveScroll(stack.protyle, true) || {}) as IScrollAttr;
scrollAttr.rootId = stack.protyle.block.rootID;
scrollAttr.focusId = stack.id;
scrollAttr.focusStart = stack.position.start;
@@ -88,23 +91,47 @@ const focusStack = async (app: App, stack: IBackStack) => {
tab,
blockId: stack.zoomId || stack.id || stack.protyle.block.rootID,
rootId: stack.protyle.block.rootID,
- action: stack.zoomId ? [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL, Constants.CB_GET_ALL, Constants.CB_GET_UNUNDO] :
- [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL, Constants.CB_GET_UNUNDO]
+ notebookId: stack.protyle.notebookId,
+ action: stack.zoomId ? [Constants.CB_GET_SCROLL, Constants.CB_GET_ALL, Constants.CB_GET_UNUNDO] :
+ [Constants.CB_GET_SCROLL, Constants.CB_GET_UNUNDO],
+ afterInitProtyle(editor) {
+ const protyle = editor.protyle;
+ if (!document.contains(protyle.element) || !tab.headElement.classList.contains("item--focus")) {
+ return;
+ }
+ if (info.data.rootID === stack.id) {
+ if (!protyle.disabled && !isPhablet()) {
+ focusByOffset(protyle.title.editElement, stack.position.start, stack.position.end);
+ }
+ } else {
+ const blockElement = Array.from(protyle.wysiwyg.element.querySelectorAll<HTMLElement>(`[data-node-id="${stack.id}"]`)).find(item =>
+ !isInEmbedBlock(item));
+ if (blockElement) {
+ if (!protyle.disabled && !isPhablet()) {
+ focusByOffset(getContenteditableElement(blockElement), stack.position.start, stack.position.end);
+ }
+ scrollCenter(protyle, blockElement, "start");
+ }
+ }
+ }
});
tab.addModel(editor);
}
});
if (window.siyuan.config.fileTree.openFilesUseCurrentTab) {
let unUpdateTab: Tab;
- // 不能 reverse, 找到也不能提前退出循环,否则 https://github.com/siyuan-note/siyuan/issues/3271
- wnd.children.forEach((item) => {
+ // 优先替换当前预览页签,保留其他已打开的预览页签。
+ wnd.children.find((item) => {
if (item.headElement && item.headElement.classList.contains("item--unupdate") && !item.headElement.classList.contains("item--pin")) {
unUpdateTab = item;
+ if (item.headElement.classList.contains("item--focus")) {
+ return true;
+ }
}
});
wnd.addTab(tab);
if (unUpdateTab) {
- wnd.removeTab(unUpdateTab.id);
+ wnd.removeTab(unUpdateTab.id, false, false);
}
} else {
wnd.addTab(tab);
@@ -123,18 +150,6 @@ const focusStack = async (app: App, stack: IBackStack) => {
item.protyle = protyle;
}
});
- if (info.data.rootID === stack.id) {
- focusByOffset(protyle.title.editElement, stack.position.start, stack.position.end);
- } else {
- Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${stack.id}"]`)).find((item: HTMLElement) => {
- if (!isInEmbedBlock(item)) {
- blockElement = item;
- return true;
- }
- });
- focusByOffset(getContenteditableElement(blockElement), stack.position.start, stack.position.end);
- scrollCenter(protyle, blockElement, "start");
- }
return true;
} else {
return false;
@@ -165,10 +180,13 @@ const focusStack = async (app: App, stack: IBackStack) => {
const focusTitle = () => {
if (stack.protyle.title.editElement.getBoundingClientRect().height === 0) {
// 切换 tab
- stack.protyle.model.parent.parent.switchTab(stack.protyle.model.parent.headElement);
+ stack.protyle.model.parent.parent.switchTab(stack.protyle.model.parent.headElement,
+ false, true, true, true, false);
stack.protyle.toolbar.range = undefined;
}
- focusByOffset(stack.protyle.title.editElement, stack.position.start, stack.position.end);
+ if (!stack.protyle.disabled && !isPhablet()) {
+ focusByOffset(stack.protyle.title.editElement, stack.position.start, stack.position.end);
+ }
};
if (stack.protyle.block.rootID === stack.id) {
if (currentZoomId !== stack.zoomId) {
@@ -176,7 +194,7 @@ const focusStack = async (app: App, stack: IBackStack) => {
protyle: stack.protyle,
id: stack.zoomId || stack.protyle.block.rootID,
isPushBack: false,
- suppressFocus: false,
+ suppressFocus: stack.protyle.disabled || isPhablet(),
callback: focusTitle,
});
} else {
@@ -196,9 +214,12 @@ const focusStack = async (app: App, stack: IBackStack) => {
) {
if (blockElement.getBoundingClientRect().height === 0) {
// 切换 tab
- stack.protyle.model.parent.parent.switchTab(stack.protyle.model.parent.headElement);
+ stack.protyle.model.parent.parent.switchTab(stack.protyle.model.parent.headElement,
+ false, true, true, true, false);
+ }
+ if (!stack.protyle.disabled && !isPhablet()) {
+ focusByOffset(getContenteditableElement(blockElement), stack.position.start, stack.position.end);
}
- focusByOffset(getContenteditableElement(blockElement), stack.position.start, stack.position.end);
scrollCenter(stack.protyle, blockElement, "start");
getAllModels().outline.forEach(item => {
if (item.blockId === stack.protyle.block.rootID) {
@@ -245,7 +266,9 @@ const focusStack = async (app: App, stack: IBackStack) => {
item.setCurrent(blockElement);
}
});
- focusByOffset(getContenteditableElement(blockElement), stack.position.start, stack.position.end);
+ if (!stack.protyle.disabled && !isPhablet()) {
+ focusByOffset(getContenteditableElement(blockElement), stack.position.start, stack.position.end);
+ }
scrollCenter(stack.protyle, blockElement, "start");
}
});
@@ -258,7 +281,7 @@ const focusStack = async (app: App, stack: IBackStack) => {
protyle: stack.protyle,
id: stack.zoomId || stack.protyle.block.rootID,
isPushBack: false,
- suppressFocus: false,
+ suppressFocus: stack.protyle.disabled || isPhablet(),
callback: () => {
Array.from(stack.protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${stack.id}"]`)).find((item: HTMLElement) => {
if (!isInEmbedBlock(item)) {
@@ -274,7 +297,9 @@ const focusStack = async (app: App, stack: IBackStack) => {
item.setCurrent(blockElement);
}
});
- focusByOffset(getContenteditableElement(blockElement), stack.position.start, stack.position.end);
+ if (!stack.protyle.disabled && !isPhablet()) {
+ focusByOffset(getContenteditableElement(blockElement), stack.position.start, stack.position.end);
+ }
scrollCenter(stack.protyle, blockElement, "start");
}
});