Skip to content

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

:sparkles: Remember tab block reading positions in read-only mode https://github.com/siyuan-note/siyuan/issues/20111

Liang Dingdb26457e2ed8
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy
index a2e012ad78..d672ee176d 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy
@@ -3035,7 +3035,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "Tabs group related content. Click a title to switch tabs, drag to reorder, or double-click to rename. Tabs can appear at the top or on the left; the selected tab is saved and synced."
+ "Data": "Tabs group related content. Click a title to switch tabs, drag to reorder, or double-click to rename. Tabs can appear at the top or on the left; the selected tab is saved and synced in edit mode. Locked documents remember the reading position locally without changing the default tab."
}
]
},
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy
index 14be2ac927..59d46e1aed 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy
@@ -3358,7 +3358,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "Use the menu beside the tabs to add, duplicate, delete or reorder tabs and choose a top or left layout. The active tab and layout are saved and synced with the document. Switching in a read-only view is temporary. Removing the tab layout preserves every title and its content in order."
+ "Data": "Use the menu beside the tabs to add, duplicate, delete or reorder tabs and choose a top or left layout. The active tab and layout are saved and synced with the document. In a locked document, the last tab viewed is saved in the local workspace without changing the document default. Published pages, globally read-only workspaces and encrypted notebooks keep this position only for the current session. Removing the tab layout preserves every title and its content in order."
}
]
},
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy
index ec8e90e46d..22daf4c88e 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy
@@ -3361,7 +3361,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "使用页签右侧的菜单新增、复制、删除或排序页签,切换顶部或左侧布局。选中的页签和布局随文档保存、同步;只读页面中的切换仅在本次查看时生效。取消页签布局会按顺序保留所有标题与正文。"
+ "Data": "使用页签右侧的菜单新增、复制、删除或排序页签,切换顶部或左侧布局。选中的页签和布局随文档保存、同步;锁定编辑的文档会在本地工作空间记住最后查看的页签,不修改文档默认页签;发布页面、全局只读工作空间及加密笔记本仅在当前会话中记住。取消页签布局会按顺序保留所有标题与正文。"
}
]
},
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy
index a105ea0b5c..26703d86a4 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy
@@ -3117,7 +3117,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "页签块将内容分组显示,点击标题切换,拖拽标题排序,双击标题重命名。支持顶部或左侧布局,选中状态会保存并同步。"
+ "Data": "页签块将内容分组显示,点击标题切换,拖拽标题排序,双击标题重命名。支持顶部或左侧布局,编辑模式的选中状态会保存并同步;锁定编辑的文档会在本地记住阅读位置,不修改默认页签。"
}
]
},
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy
index cdbada0837..32d2a6fc83 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy
@@ -3035,7 +3035,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "頁籤區塊將內容分組顯示,點擊標題切換,拖曳標題排序,按兩下標題重新命名。支援頂部或左側配置,選取狀態會儲存並同步。"
+ "Data": "頁籤區塊將內容分組顯示,點擊標題切換,拖曳標題排序,按兩下標題重新命名。支援頂部或左側配置,編輯模式的選取狀態會儲存並同步;鎖定編輯的文件會在本機記住閱讀位置,不修改預設頁籤。"
}
]
},
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy
index 95923a7d56..a79c06f009 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy
@@ -3359,7 +3359,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "使用頁籤右側的選單新增、複製、刪除或排序頁籤,切換頂部或左側版面配置。選取的頁籤與版面配置會隨文件儲存、同步;唯讀頁面的切換僅於本次檢視生效。取消頁籤版面配置會依序保留所有標題與內文。"
+ "Data": "使用頁籤右側的選單新增、複製、刪除或排序頁籤,切換頂部或左側版面配置。選取的頁籤與版面配置會隨文件儲存、同步;鎖定編輯的文件會在本機工作空間記住最後檢視的頁籤,不修改文件預設頁籤;發佈頁面、全域唯讀工作空間及加密筆記本僅於目前工作階段記住。取消頁籤版面配置會依序保留所有標題與內文。"
}
]
},
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy
index 0a09518a6c..6673d62775 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy
@@ -3229,7 +3229,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "タブブロックは内容をグループに分けて表示します。タイトルのクリックで切り替え、ドラッグで並べ替え、ダブルクリックで名前を変更できます。上部または左側に配置でき、選択したタブは保存・同期されます。"
+ "Data": "タブブロックは内容をグループに分けて表示します。タイトルのクリックで切り替え、ドラッグで並べ替え、ダブルクリックで名前を変更できます。上部または左側に配置でき、編集モードで選択したタブは保存・同期されます。編集をロックしたドキュメントでは、既定のタブを変更せず、閲覧位置をローカルに記憶します。"
}
]
},
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy
index bddc4e6a92..755ab85545 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy
@@ -3490,7 +3490,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "タブ右側のメニューで、タブの追加、複製、削除、並べ替え、および上部/左側の配置を選べます。選択中のタブと配置はドキュメントとともに保存・同期されます。読み取り専用画面での切り替えは一時的です。タブ配置を解除すると、すべてのタイトルと本文が順番に残ります。"
+ "Data": "タブ右側のメニューで、タブの追加、複製、削除、並べ替え、および上部/左側の配置を選べます。選択中のタブと配置はドキュメントとともに保存・同期されます。編集をロックしたドキュメントでは、最後に表示したタブをローカルワークスペースに記憶し、ドキュメントの既定のタブは変更しません。公開ページ、ワークスペース全体が読み取り専用の場合、および暗号化ノートブックでは、現在のセッション中のみ記憶します。タブ配置を解除すると、すべてのタイトルと本文が順番に残ります。"
}
]
},
diff --git a/app/src/constants.ts b/app/src/constants.ts
index f9756d1edb..04ee35f876 100644
--- a/app/src/constants.ts
+++ b/app/src/constants.ts
@@ -210,6 +210,7 @@ export abstract class Constants {
public static readonly LOCAL_RECENT_DOCS = "local-recent-docs";
public static readonly LOCAL_CLOSED_TABS = "local-closed-tabs";
public static readonly LOCAL_AV_CALENDAR_MODES = "local-av-calendar-modes";
+ public static readonly LOCAL_TABS_READING = "local-tabs-reading";
// dialog
public static readonly DIALOG_CONFIRM = "dialog-confirm";
diff --git a/app/src/protyle/render/tabsRender.ts b/app/src/protyle/render/tabsRender.ts
index 94a46b7078..e82b5be75a 100644
--- a/app/src/protyle/render/tabsRender.ts
+++ b/app/src/protyle/render/tabsRender.ts
@@ -10,6 +10,8 @@ export interface ITabsRenderOptions {
label?: string;
addLabel?: string;
select?: (tabs: HTMLElement, id: string) => void;
+ restore?: (tabs: HTMLElement) => string;
+ remember?: (tabs: HTMLElement, id: string) => void;
activate?: (item: HTMLElement) => void;
rename?: (item: HTMLElement) => void;
add?: (tabs: HTMLElement) => void;
@@ -166,6 +168,9 @@ export const tabsRender = (element: Element, options: ITabsRenderOptions = {}) =
}
state.active = id;
state.pending = undefined;
+ if (persist) {
+ controller.options.remember?.(tabs, id);
+ }
if (persist && !controller.options.readonly?.(tabs)) {
controller.options.select?.(tabs, id);
}
@@ -192,7 +197,9 @@ export const tabsRender = (element: Element, options: ITabsRenderOptions = {}) =
const source = resolveTabID(ids, tabs.getAttribute("tabs-active-id"));
let state = states.get(tabs);
if (!state || state.owner !== controller) {
- state = {owner: controller, active: source, source, instance: `siyuan-tabs-${++instanceID}`};
+ const restored = controller.options.restore?.(tabs);
+ state = {owner: controller, active: ids.includes(restored) ? restored : source,
+ source, instance: `siyuan-tabs-${++instanceID}`};
states.set(tabs, state);
}
const current = items.find(item => itemID(item) === state.active);
diff --git a/app/src/protyle/util/compatibility.ts b/app/src/protyle/util/compatibility.ts
index f77d13a65c..87d70cf4c0 100644
--- a/app/src/protyle/util/compatibility.ts
+++ b/app/src/protyle/util/compatibility.ts
@@ -825,6 +825,7 @@ export const getLocalStorage = (cb: () => void) => {
defaultStorage[Constants.LOCAL_MOVE_PATH] = {keys: [], k: ""};
defaultStorage[Constants.LOCAL_RECENT_DOCS] = {type: "viewedAt"}; // TRecentDocsSort
defaultStorage[Constants.LOCAL_AV_CALENDAR_MODES] = {};
+ defaultStorage[Constants.LOCAL_TABS_READING] = {};
[Constants.LOCAL_EXPORTIMG, Constants.LOCAL_EXPORTPATH, Constants.LOCAL_SEARCHKEYS, Constants.LOCAL_PDFTHEME, Constants.LOCAL_BAZAAR,
Constants.LOCAL_EXPORTWORD, Constants.LOCAL_EXPORTPDF, Constants.LOCAL_DOCINFO, Constants.LOCAL_MOBILE_TABS,
@@ -835,7 +836,7 @@ export const getLocalStorage = (cb: () => void) => {
Constants.LOCAL_DIALOGPOSITION, Constants.LOCAL_SEARCHUNREF, Constants.LOCAL_HISTORY,
Constants.LOCAL_OUTLINE, Constants.LOCAL_FILEPOSITION, Constants.LOCAL_FILESPATHS, Constants.LOCAL_IMAGES,
Constants.LOCAL_PLUGIN_DOCKS, Constants.LOCAL_EMOJIS, Constants.LOCAL_MOVE_PATH, Constants.LOCAL_RECENT_DOCS,
- Constants.LOCAL_CLOSED_TABS, Constants.LOCAL_AV_CALENDAR_MODES].forEach((key) => {
+ Constants.LOCAL_CLOSED_TABS, Constants.LOCAL_AV_CALENDAR_MODES, Constants.LOCAL_TABS_READING].forEach((key) => {
const value = response.data[key];
if (typeof value === "string") {
try {
diff --git a/app/src/protyle/util/focusRestore.test.ts b/app/src/protyle/util/focusRestore.test.ts
index 4667487fe0..d84b76f38e 100644
--- a/app/src/protyle/util/focusRestore.test.ts
+++ b/app/src/protyle/util/focusRestore.test.ts
@@ -48,6 +48,17 @@ describe("saved focus respects persisted tab selection", () => {
inner.append(new FocusElement("tab-item", {"data-node-id": "inner-active"}));
assert.equal(getSavedTabFocusTarget(first.asElement()), outer.asElement());
});
+ it("prioritizes the readonly reading position over stale focus and falls back after deletion", () => {
+ const tabs = new FocusElement("tabs", {"tabs-active-id": "first"});
+ const first = tabs.append(new FocusElement("tab-item", {"data-node-id": "first"}));
+ const second = tabs.append(new FocusElement("tab-item", {"data-node-id": "second"}));
+ const oldFocus = first.append(new FocusElement());
+ const readingFocus = second.append(new FocusElement());
+ assert.equal(getSavedTabFocusTarget(oldFocus.asElement(), () => "second"), tabs.asElement());
+ assert.equal(getSavedTabFocusTarget(readingFocus.asElement(), () => "second"), readingFocus.asElement());
+ assert.equal(getSavedTabFocusTarget(oldFocus.asElement(), () => "deleted"), oldFocus.asElement());
+ assert.equal(getSavedTabFocusTarget(oldFocus.asElement(), () => undefined), oldFocus.asElement());
+ });
it("leaves ordinary focus and a missing target unchanged", () => {
const paragraph = new FocusElement();
assert.equal(getSavedTabFocusTarget(paragraph.asElement()), paragraph.asElement());
diff --git a/app/src/protyle/util/focusRestore.ts b/app/src/protyle/util/focusRestore.ts
index e863d6ba62..21f10e6d23 100644
--- a/app/src/protyle/util/focusRestore.ts
+++ b/app/src/protyle/util/focusRestore.ts
@@ -8,8 +8,8 @@ export const shouldFocusAfterZoom = (options: {
export const hasFocusOffsets = (scrollAttr?: IScrollAttr) => Boolean(scrollAttr?.focusId) &&
typeof scrollAttr.focusStart === "number" && typeof scrollAttr.focusEnd === "number";
-// 恢复光标时以持久化的页签选择为准,过期光标不能重新激活隐藏页。
-export const getSavedTabFocusTarget = (element: Element): Element => {
+// 恢复光标时优先使用阅读位置,其次使用文档默认页签,过期光标不能重新激活隐藏页。
+export const getSavedTabFocusTarget = (element: Element, getActiveID?: (tabs: Element) => string): Element => {
let target = element;
for (let item = element?.closest(".tab-item"); item; item = item.parentElement?.closest(".tab-item")) {
const tabs = item.parentElement;
@@ -17,7 +17,9 @@ export const getSavedTabFocusTarget = (element: Element): Element => {
continue;
}
const items = Array.from(tabs.children).filter(child => child.classList.contains("tab-item"));
- const active = items.find(child => child.getAttribute("data-node-id") === tabs.getAttribute("tabs-active-id")) || items[0];
+ const readingID = getActiveID?.(tabs);
+ const active = items.find(child => child.getAttribute("data-node-id") === readingID) ||
+ items.find(child => child.getAttribute("data-node-id") === tabs.getAttribute("tabs-active-id")) || items[0];
if (active !== item) {
target = tabs;
}
diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.ts
index 6032435dac..ba2bed141c 100644
--- a/app/src/protyle/util/onGet.ts
+++ b/app/src/protyle/util/onGet.ts
@@ -8,6 +8,7 @@ import {resolveVisibleListMindmapBlock} from "../render/listMindmap/render";
import {highlightRender} from "../render/highlightRender";
import {blockRender} from "../render/blockRender";
import {revealTabsForTarget} from "../render/tabsRender";
+import {getTabReadingID} from "../wysiwyg/tabsReading";
import {bgFade, scrollCenter} from "../../util/highlightById";
/// #if !MOBILE
import {pushBack} from "../../util/backForward";
@@ -687,7 +688,7 @@ const focusElementById = (protyle: IProtyle, action: string[], scrollAttr?: IScr
const hasScrollTop = scrollAttr && typeof scrollAttr.scrollTop === "number";
const savedFocusElement = focusElement;
if (hasScrollTop && scrollAttr.focusId && !action.includes(Constants.CB_GET_HL)) {
- focusElement = getSavedTabFocusTarget(focusElement);
+ focusElement = getSavedTabFocusTarget(focusElement, tabs => getTabReadingID(protyle, tabs as HTMLElement));
}
if (action.includes(Constants.CB_GET_HL)) {
preventScroll(protyle); // 搜索页签滚动会导致再次请求
diff --git a/app/src/protyle/wysiwyg/tabs.ts b/app/src/protyle/wysiwyg/tabs.ts
index 84578d577c..ef8378448e 100644
--- a/app/src/protyle/wysiwyg/tabs.ts
+++ b/app/src/protyle/wysiwyg/tabs.ts
@@ -18,6 +18,7 @@ import {hideElements} from "../ui/hideElements";
import {getTaskStatusItems} from "./taskStatusDialog";
import {canFocusTabItem, getFocusedTabItem, prepareFocusedTabItem} from "./tabsFocus";
import {zoomOut} from "../../menus/protyle";
+import {getTabReadingID, saveTabReadingID} from "./tabsReading";
const boundFocusedTitles = new WeakSet<HTMLElement>();
@@ -226,6 +227,8 @@ export const initEditorTabs = (protyle: IProtyle) => {
tabsRender(root, {
prepare: () => prepareFocusedTabItem(protyle),
readonly: tabs => !canEdit(protyle, tabs || root),
+ restore: tabs => getTabReadingID(protyle, tabs),
+ remember: (tabs, id) => saveTabReadingID(protyle, tabs, id),
label: window.siyuan.languages.tabItem,
addLabel: window.siyuan.languages.newTabItem,
taskLabel: window.siyuan.languages.task,
diff --git a/app/src/protyle/wysiwyg/tabsReading.test.ts b/app/src/protyle/wysiwyg/tabsReading.test.ts
new file mode 100644
index 0000000000..cc18d5385f
--- /dev/null
+++ b/app/src/protyle/wysiwyg/tabsReading.test.ts
@@ -0,0 +1,168 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import * as ts from "typescript";
+
+const storageKey = "local-tabs-reading";
+const compile = (source: string) => ts.transpileModule(source, {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},
+}).outputText;
+const readingSource = compile(readFileSync("src/protyle/wysiwyg/tabsReading.ts", "utf8"));
+const renderer = ts.createSourceFile("tabsRender.ts", readFileSync("src/protyle/render/tabsRender.ts", "utf8"),
+ ts.ScriptTarget.ES2021, true);
+let selectSource: string;
+let restoreSource: string;
+const visit = (node: ts.Node) => {
+ if (ts.isMethodDeclaration(node) && node.name.getText(renderer) === "select") {
+ selectSource = node.body.getText(renderer);
+ }
+ if (ts.isIfStatement(node) && node.expression.getText(renderer) === "!state || state.owner !== controller") {
+ restoreSource = node.thenStatement.getText(renderer);
+ }
+ node.forEachChild(visit);
+};
+visit(renderer);
+assert.ok(selectSource);
+assert.ok(restoreSource);
+
+const fixture = (storage: Record<string, any> = {}) => {
+ const writes: Record<string, string>[] = [];
+ const siyuan = {storage, config: {readonly: false}, isPublish: false};
+ const api = {} as typeof import("./tabsReading");
+ const root = {};
+ const protyle = {disabled: true, lite: false, notebookId: "ordinary", options: {action: [] as string[]},
+ wysiwyg: {element: root}};
+ let excluded = false;
+ let inside = true;
+ const block = (id = "tabs") => ({dataset: {nodeId: id}, getAttribute: () => "a",
+ closest: (selector: string) => selector === ".protyle-wysiwyg" ? (inside ? root : null) : excluded ? root : null});
+ const read = (tabs = block()) => api.getTabReadingID(protyle as IProtyle, tabs as unknown as HTMLElement);
+ const save = (id: string, tabs = block()) => api.saveTabReadingID(protyle as IProtyle, tabs as unknown as HTMLElement, id);
+ runInNewContext(readingSource, {exports: api, window: {siyuan}, require: (id: string) => {
+ if (id === "../../constants") {
+ return {Constants: {LOCAL_TABS_READING: storageKey, CB_GET_HISTORY: "history"}};
+ }
+ if (id === "../../util/pathName") {
+ return {isEncryptedBox: (notebook: string) => notebook === "encrypted"};
+ }
+ assert.equal(id, "../util/compatibility");
+ return {setStorageVal: (key: string, selections: Record<string, string>) => {
+ assert.equal(key, storageKey);
+ writes.push(JSON.parse(JSON.stringify(selections)));
+ }};
+ }});
+ return {siyuan, protyle, writes, block, read, save,
+ exclude: () => { excluded = true; }, outside: () => { inside = false; }};
+};
+
+test("readonly selection survives reopening and restart without changing document attributes", () => {
+ const f = fixture();
+ const tabs = f.block();
+ f.save("b", tabs);
+ assert.equal(tabs.getAttribute(), "a");
+ assert.equal(f.read(f.block()), "b");
+ assert.equal(f.writes.length, 1);
+ const restarted = fixture({[storageKey]: f.writes[0]});
+ assert.equal(restarted.read(), "b");
+ assert.equal(restarted.read(restarted.block("other")), undefined);
+ assert.equal(fixture().read(), undefined);
+ f.save("b");
+ assert.equal(f.writes.length, 1);
+});
+
+test("editing uses document defaults and clears an old readonly selection", () => {
+ const f = fixture();
+ f.save("b");
+ f.protyle.disabled = false;
+ assert.equal(f.read(), undefined);
+ f.save("a");
+ assert.deepEqual(f.writes[1], {});
+ f.protyle.disabled = true;
+ assert.equal(f.read(), undefined);
+});
+
+test("publish, global readonly and encrypted notebooks retain only session selections", () => {
+ for (const mode of ["publish", "readonly", "encrypted"]) {
+ const f = fixture({[storageKey]: {other: "unchanged"}});
+ f.siyuan.isPublish = mode === "publish";
+ f.siyuan.config.readonly = mode === "readonly";
+ f.protyle.notebookId = mode === "encrypted" ? "encrypted" : "ordinary";
+ f.save("b");
+ assert.equal(f.read(f.block()), "b");
+ assert.equal(f.writes.length, 0);
+ assert.deepEqual(f.siyuan.storage[storageKey], {other: "unchanged"});
+ f.siyuan.storage = {};
+ assert.equal(f.read(), undefined, "a different workspace cannot inherit session selections");
+ }
+});
+
+test("history, lite editors, embedded previews and foreign roots do not restore or save reading positions", () => {
+ for (const mode of ["history", "lite", "preview", "foreign"]) {
+ const f = fixture({[storageKey]: {tabs: "b"}});
+ if (mode === "history") { f.protyle.options.action.push("history"); }
+ if (mode === "lite") { f.protyle.lite = true; }
+ if (mode === "preview") { f.exclude(); }
+ if (mode === "foreign") { f.outside(); }
+ assert.equal(f.read(), undefined);
+ f.save("a");
+ assert.equal(f.writes.length, 0);
+ assert.equal(f.siyuan.storage[storageKey].tabs, "b");
+ }
+});
+
+test("reading records tolerate malformed storage and keep the most recent thousand blocks", () => {
+ for (const value of [null, "invalid", [], {tabs: 42}] as unknown[]) {
+ const f = fixture({[storageKey]: value});
+ assert.equal(f.read(), undefined);
+ f.save("b");
+ assert.equal(f.read(), "b");
+ }
+ const saved = Object.fromEntries(Array.from({length: 1000}, (_, index) => [`tabs-${index}`, "a"]));
+ const f = fixture({[storageKey]: saved});
+ f.save("b", f.block("tabs-0"));
+ f.save("b");
+ assert.equal(Object.keys(f.siyuan.storage[storageKey]).length, 1000);
+ assert.equal(f.siyuan.storage[storageKey]["tabs-1"], undefined);
+ assert.equal(f.siyuan.storage[storageKey]["tabs-0"], "b");
+});
+
+test("renderer remembers readonly navigation, guards document writes and leaves temporary reveals unsaved", () => {
+ const f = fixture();
+ const tabs = f.block();
+ const states = new WeakMap();
+ let documentWrites = 0;
+ const controller = {render() {}, options: {
+ readonly: () => f.protyle.disabled, remember: (_tabs: unknown, id: string) => f.save(id),
+ select: () => documentWrites++,
+ }};
+ const state = {owner: controller, active: "a", pending: undefined as string | undefined};
+ states.set(tabs, state);
+ const select = (id: string, persist = true) => runInNewContext(compile(`(() => ${selectSource})();`), {
+ tabs, id, persist, states, controller, itemID: (item: {id: string}) => item.id,
+ getTabItems: () => [{id: "a", dataset: {}}, {id: "b", dataset: {}}],
+ });
+ select("b");
+ assert.equal(state.active, "b");
+ assert.equal(f.read(), "b");
+ assert.equal(documentWrites, 0);
+ select("a", false);
+ assert.equal(state.active, "a");
+ assert.equal(f.read(), "b");
+ select("missing");
+ assert.equal(state.active, "a");
+ f.protyle.disabled = false;
+ select("a");
+ assert.equal(documentWrites, 1);
+ assert.deepEqual(f.writes.at(-1), {});
+});
+
+test("renderer restores valid reading positions and falls back to document defaults after deletion", () => {
+ for (const restored of ["b", "missing", undefined]) {
+ const context = {states: new WeakMap(), tabs: {}, controller: {options: {restore: () => restored}},
+ ids: ["a", "b", "c"], source: "c", instanceID: 0, state: undefined as {active: string, source: string}};
+ runInNewContext(compile(restoreSource), context);
+ assert.equal(context.state.active, restored === "b" ? "b" : "c");
+ assert.equal(context.state.source, "c");
+ }
+});
diff --git a/app/src/protyle/wysiwyg/tabsReading.ts b/app/src/protyle/wysiwyg/tabsReading.ts
new file mode 100644
index 0000000000..86bffe5697
--- /dev/null
+++ b/app/src/protyle/wysiwyg/tabsReading.ts
@@ -0,0 +1,57 @@
+import {Constants} from "../../constants";
+import {isEncryptedBox} from "../../util/pathName";
+import {setStorageVal} from "../util/compatibility";
+
+const sessionSelections = new WeakMap<object, Record<string, string>>();
+
+const canRemember = (protyle: IProtyle, tabs: HTMLElement) => !!tabs.dataset.nodeId && !protyle.lite &&
+ !protyle.options.action.includes(Constants.CB_GET_HISTORY) &&
+ !tabs.closest(".protyle-wysiwyg__embed, .mindmap-view__preview-block") &&
+ tabs.closest(".protyle-wysiwyg") === protyle.wysiwyg.element;
+
+// 无写权限及加密笔记本的阅读位置仅保留在当前工作空间会话中。
+const isSessionOnly = (protyle: IProtyle) => window.siyuan.config.readonly || window.siyuan.isPublish ||
+ isEncryptedBox(protyle.notebookId);
+
+const getSelections = (protyle: IProtyle): Record<string, string> => {
+ const storage = window.siyuan.storage;
+ if (!storage) {
+ return {};
+ }
+ if (isSessionOnly(protyle)) {
+ return sessionSelections.get(storage) || {};
+ }
+ const saved = storage[Constants.LOCAL_TABS_READING];
+ return saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
+};
+
+export const getTabReadingID = (protyle: IProtyle, tabs: HTMLElement): string => {
+ if (!protyle.disabled || !canRemember(protyle, tabs)) {
+ return undefined;
+ }
+ const id = getSelections(protyle)[tabs.dataset.nodeId];
+ return typeof id === "string" ? id : undefined;
+};
+
+export const saveTabReadingID = (protyle: IProtyle, tabs: HTMLElement, id: string) => {
+ if (!canRemember(protyle, tabs) || !window.siyuan.storage) {
+ return;
+ }
+ const saved = getSelections(protyle);
+ const key = tabs.dataset.nodeId;
+ if ((protyle.disabled && saved[key] === id) || (!protyle.disabled && !saved[key])) {
+ return;
+ }
+ // 最近选择移到末尾,限制记录数量;编辑时清除旧阅读位置,沿用文档的默认激活项。
+ const entries = Object.entries(saved).filter(([blockID, activeID]) => blockID !== key && typeof activeID === "string");
+ if (protyle.disabled) {
+ entries.push([key, id]);
+ }
+ const selections = Object.fromEntries(entries.slice(-1000));
+ if (isSessionOnly(protyle)) {
+ sessionSelections.set(window.siyuan.storage, selections);
+ } else {
+ window.siyuan.storage[Constants.LOCAL_TABS_READING] = selections;
+ void setStorageVal(Constants.LOCAL_TABS_READING, selections);
+ }
+};