Skip to content

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

:bug: Preserve mobile tab positions when saving layout https://github.com/siyuan-note/siyuan/issues/20126

Danielc4bfdf935ce0
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 03104a5c5e..fd051ed7fc 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "تعذّر حفظ تخطيط الجوال. يُرجى المحاولة مرة أخرى.",
"ocrThresholdSettings": "عتبات التعرف",
"ocrReasoningEffortTip": "يتبع الإعداد الافتراضي سلوك النموذج؛ يعطل خيار بدون التفكير أو يقلله حسب دعم المزود والنموذج",
"mobileToolbarNoSelection": "دون تحديد نص",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 92879b1567..b035a8c4f2 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "Das mobile Layout konnte nicht gespeichert werden. Bitte erneut versuchen.",
"ocrThresholdSettings": "Erkennungsschwellen",
"ocrReasoningEffortTip": "Standard folgt dem Modellverhalten; Keine deaktiviert oder minimiert das Denken, abhängig von Anbieter und Modell",
"mobileToolbarNoSelection": "Kein Text ausgewählt",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 4dab23cd76..63fddeeebf 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "Could not save the mobile layout. Please try again.",
"ocrThresholdSettings": "Recognition thresholds",
"ocrReasoningEffortTip": "Default follows model behavior; None disables or minimizes thinking, depending on provider and model support",
"mobileToolbarNoSelection": "No text selected",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index f75eba82f4..7a239cf187 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "No se pudo guardar el diseño móvil. Inténtalo de nuevo.",
"ocrThresholdSettings": "Umbrales de reconocimiento",
"ocrReasoningEffortTip": "Predeterminado sigue el comportamiento del modelo; Ninguno desactiva o minimiza el razonamiento según el proveedor y el modelo",
"mobileToolbarNoSelection": "Sin texto seleccionado",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 32409e240a..f3985ac4dc 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "Impossible d'enregistrer la disposition mobile. Veuillez réessayer.",
"ocrThresholdSettings": "Seuils de reconnaissance",
"ocrReasoningEffortTip": "Par défaut suit le comportement du modèle ; Aucun désactive ou minimise le raisonnement selon le fournisseur et le modèle",
"mobileToolbarNoSelection": "Aucun texte sélectionné",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 6b49297ad2..2e87d5f18b 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "לא ניתן לשמור את העיצוב לנייד. יש לנסות שוב.",
"ocrThresholdSettings": "ספי זיהוי",
"ocrReasoningEffortTip": "ברירת המחדל פועלת לפי התנהגות המודל; ללא מכבה או מצמצם את החשיבה בהתאם לתמיכת הספק והמודל",
"mobileToolbarNoSelection": "ללא טקסט נבחר",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index c12e005605..ae05438b7e 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "मोबाइल लेआउट सहेजा नहीं जा सका। कृपया फिर से प्रयास करें।",
"ocrThresholdSettings": "पहचान की सीमाएँ",
"ocrReasoningEffortTip": "डिफ़ॉल्ट मॉडल के व्यवहार का पालन करता है; कोई नहीं विकल्प प्रदाता और मॉडल के समर्थन के अनुसार सोच को बंद या न्यूनतम करता है",
"mobileToolbarNoSelection": "कोई पाठ चयनित नहीं",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index d310d47b92..c37adec252 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "Tidak dapat menyimpan tata letak seluler. Silakan coba lagi.",
"ocrThresholdSettings": "Ambang pengenalan",
"ocrReasoningEffortTip": "Default mengikuti perilaku model; Tidak ada menonaktifkan atau meminimalkan pemikiran sesuai dukungan penyedia dan model",
"mobileToolbarNoSelection": "Tidak ada teks dipilih",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 5387c66a1a..37747032ed 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "Impossibile salvare il layout mobile. Riprova.",
"ocrThresholdSettings": "Soglie di riconoscimento",
"ocrReasoningEffortTip": "Predefinito segue il comportamento del modello; Nessuno disattiva o riduce al minimo il ragionamento secondo il provider e il modello",
"mobileToolbarNoSelection": "Nessun testo selezionato",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index f430a09f7e..7b6553060e 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "モバイル端末のレイアウトを保存できませんでした。もう一度お試しください。",
"ocrThresholdSettings": "認識のしきい値",
"ocrReasoningEffortTip": "デフォルトはモデルの動作に従います。「なし」は思考を無効化または最小化しますが、対応状況はプロバイダーとモデルによって異なります",
"mobileToolbarNoSelection": "テキスト未選択",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 61ec2340c2..533c10fa8c 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "모바일 레이아웃을 저장하지 못했습니다. 다시 시도해 주세요.",
"ocrThresholdSettings": "인식 임계값",
"ocrReasoningEffortTip": "기본값은 모델 동작을 따릅니다. 없음은 사고를 끄거나 최소화하며, 지원 여부는 공급자와 모델에 따라 다릅니다",
"mobileToolbarNoSelection": "텍스트 선택 안 함",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 502ecbdc85..0815771604 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "De mobiele indeling kon niet worden opgeslagen. Probeer het opnieuw.",
"ocrThresholdSettings": "Herkenningsdrempels",
"ocrReasoningEffortTip": "Standaard volgt het modelgedrag; Geen schakelt denken uit of beperkt het tot een minimum, afhankelijk van de aanbieder en het model",
"mobileToolbarNoSelection": "Geen tekst geselecteerd",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 0a7e882b9d..2b4dbe3562 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "Nie udało się zapisać układu mobilnego. Spróbuj ponownie.",
"ocrThresholdSettings": "Progi rozpoznawania",
"ocrReasoningEffortTip": "Domyślne zachowuje działanie modelu; Brak wyłącza lub minimalizuje rozumowanie zależnie od obsługi przez dostawcę i model",
"mobileToolbarNoSelection": "Brak zaznaczonego tekstu",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 7fd1fc1a18..3ec2abadd6 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "Não foi possível salvar o layout móvel. Tente novamente.",
"ocrThresholdSettings": "Limiares de reconhecimento",
"ocrReasoningEffortTip": "Padrão segue o comportamento do modelo; Nenhum desativa ou minimiza o raciocínio conforme o suporte do provedor e do modelo",
"mobileToolbarNoSelection": "Sem texto selecionado",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 1370463add..8e9a482f67 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "Не удалось сохранить мобильный макет. Повторите попытку.",
"ocrThresholdSettings": "Пороги распознавания",
"ocrReasoningEffortTip": "По умолчанию используется поведение модели; Нет отключает или минимизирует рассуждения в зависимости от провайдера и модели",
"mobileToolbarNoSelection": "Текст не выделен",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 727c4ee0fb..558dfe794c 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "Mobilné rozloženie sa nepodarilo uložiť. Skúste to znova.",
"ocrThresholdSettings": "Prahy rozpoznávania",
"ocrReasoningEffortTip": "Predvolené používa správanie modelu; Žiadne vypne alebo minimalizuje uvažovanie podľa podpory poskytovateľa a modelu",
"mobileToolbarNoSelection": "Žiadny vybratý text",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index b8ae921a6d..f1a6631813 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "Nije moguće sačuvati mobilni raspored. Pokušajte ponovo.",
"ocrThresholdSettings": "Прагови препознавања",
"ocrReasoningEffortTip": "Подразумевано прати понашање модела; Без искључује или своди размишљање на минимум у зависности од подршке добављача и модела",
"mobileToolbarNoSelection": "Без изабраног текста",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 641d8c0900..6d1ac695d9 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "ไม่สามารถบันทึกเค้าโครงบนมือถือได้ โปรดลองอีกครั้ง",
"ocrThresholdSettings": "เกณฑ์การรู้จำ",
"ocrReasoningEffortTip": "ค่าเริ่มต้นใช้พฤติกรรมของโมเดล ส่วนไม่มีจะปิดหรือลดการคิดให้เหลือน้อยที่สุดตามการรองรับของผู้ให้บริการและโมเดล",
"mobileToolbarNoSelection": "ไม่มีข้อความที่เลือก",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index abed28c39d..35081be83a 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "Mobil düzen kaydedilemedi. Lütfen tekrar deneyin.",
"ocrThresholdSettings": "Tanıma eşikleri",
"ocrReasoningEffortTip": "Varsayılan, model davranışını izler; Yok, sağlayıcı ve model desteğine göre düşünmeyi kapatır veya en aza indirir",
"mobileToolbarNoSelection": "Metin seçilmedi",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 611dc18252..22568b76fa 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "Не вдалося зберегти мобільний макет. Спробуйте ще раз.",
"ocrThresholdSettings": "Пороги розпізнавання",
"ocrReasoningEffortTip": "За замовчуванням використовується поведінка моделі; Немає вимикає або мінімізує міркування залежно від підтримки провайдера та моделі",
"mobileToolbarNoSelection": "Текст не виділено",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index ed9655cae5..95d683a7ec 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "移动端布局保存失败,请重试。",
"ocrThresholdSettings": "识别阈值",
"ocrReasoningEffortTip": "默认沿用模型行为;无表示关闭或尽量减少思考,是否支持取决于提供商和模型",
"mobileToolbarNoSelection": "未选中文本",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index ccb9e74848..fc8b65a107 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,5 @@
{
+ "mobileLayoutSaveError": "行動端佈局儲存失敗,請重試。",
"ocrThresholdSettings": "辨識閾值",
"ocrReasoningEffortTip": "預設沿用模型行為;無表示關閉或盡量減少思考,是否支援取決於提供商和模型",
"mobileToolbarNoSelection": "未選取文字",
diff --git a/app/src/dialog/processSystem.ts b/app/src/dialog/processSystem.ts
index b9469c4339..b1e72c6c7a 100644
--- a/app/src/dialog/processSystem.ts
+++ b/app/src/dialog/processSystem.ts
@@ -17,7 +17,7 @@ import {confirmDialog} from "./confirmDialog";
import {escapeHtml} from "../util/escape";
import {needSubscribe} from "../util/needSubscribe";
import {hideAllElements} from "../protyle/ui/hideElements";
-import {saveScroll} from "../protyle/scroll/saveScroll";
+import {saveMobileLayout} from "../mobile/util/saveLayout";
import {isInAndroid, isInHarmony, isInIOS, setStorageVal} from "../protyle/util/compatibility";
import {emitToPlugins} from "../plugin/EventBusCore";
import {createHostQuitGuard} from "./hostQuit";
@@ -144,10 +144,8 @@ export const lockScreen = async () => {
}
});
/// #else
- if (window.siyuan.mobile.editor) {
- await saveScroll(window.siyuan.mobile.editor.protyle);
- fetchPost("/api/system/logoutAuth");
- }
+ await saveMobileLayout();
+ fetchPost("/api/system/logoutAuth");
/// #endif
};
@@ -228,8 +226,9 @@ export const exitSiYuan = async (setCurrentWorkspace = true) => {
}
/// #endif
/// #if MOBILE
- if (window.siyuan.mobile.editor) {
- await saveScroll(window.siyuan.mobile.editor.protyle);
+ if (!await saveMobileLayout()) {
+ showMessage(window.siyuan.languages.mobileLayoutSaveError, 6000, "error");
+ return;
}
/// #endif
if (!getHostCapabilities().ownsKernel) {
diff --git a/app/src/mobile/editor.ts b/app/src/mobile/editor.ts
index 5de4c33d21..b73550a22d 100644
--- a/app/src/mobile/editor.ts
+++ b/app/src/mobile/editor.ts
@@ -70,7 +70,7 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[
afterOpen?: (protyle: IProtyle) => void, forceReload = false,
isValid: () => boolean = () => true, signal?: AbortSignal,
scrollAttr?: IScrollAttr, updateRecent = true,
- onFailure?: (invalid?: boolean) => void, keepPanels = false) => {
+ onFailure?: (invalid?: boolean, editorUnchanged?: boolean) => void, keepPanels = false) => {
invalidateMobileReferenceOpen();
const closing = closeMobileEditorSheets();
if (closing) {
@@ -79,11 +79,11 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[
loadMobileFileById(app, id, action, scrollPosition, notebookId, afterOpen, forceReload,
isValid, signal, scrollAttr, updateRecent, onFailure, keepPanels);
} else {
- onFailure?.();
+ onFailure?.(undefined, true);
}
}).catch(error => {
console.error(error);
- onFailure?.();
+ onFailure?.(undefined, true);
});
return;
}
@@ -122,7 +122,7 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[
if (titleHidden && isValid() && window.siyuan.mobile.editor?.protyle.wysiwyg.element.childElementCount > 0) {
setEditor();
}
- onFailure?.(invalid);
+ onFailure?.(invalid, !titleHidden);
};
if (!isValid()) {
fail();
diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.ts
index cab146345d..30102e05fb 100644
--- a/app/src/mobile/index.ts
+++ b/app/src/mobile/index.ts
@@ -26,6 +26,7 @@ import {
} from "./util/touch";
import {fetchPost} from "../util/fetch";
import {initFramework} from "./util/initFramework";
+import {saveMobileLayout} from "./util/saveLayout";
import {finishMobileStartup} from "./util/setEmpty";
import {initAssets} from "../util/assets";
import {bootSync, lockScreen} from "../dialog/processSystem";
@@ -185,11 +186,16 @@ class App {
};
}
window.addEventListener("beforeunload", () => {
- window.siyuan.mobile.tabs?.save();
+ void saveMobileLayout();
}, false);
window.addEventListener("pagehide", () => {
- window.siyuan.mobile.tabs?.save();
+ void saveMobileLayout();
}, false);
+ document.addEventListener("visibilitychange", () => {
+ if (document.visibilityState === "hidden") {
+ void saveMobileLayout();
+ }
+ });
// 判断手机横竖屏状态
bindMobileOrientationChange(() => {
updateCardHV();
diff --git a/app/src/mobile/tabs/MobileTabs.save.test.ts b/app/src/mobile/tabs/MobileTabs.save.test.ts
new file mode 100644
index 0000000000..3758167555
--- /dev/null
+++ b/app/src/mobile/tabs/MobileTabs.save.test.ts
@@ -0,0 +1,406 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import test from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import * as scrollRequest from "../../protyle/scroll/scrollRequest";
+import * as stateFunctions from "./mobileTabsState";
+
+const constants = {LOCAL_MOBILE_TABS: "mobileTabs", LOCAL_DOCINFO: "docInfo", LOCAL_FILEPOSITION: "positions",
+ CB_GET_SCROLL: "scroll", CB_GET_HL: "hl", CB_GET_CONTEXT: "context", CB_GET_ROOTSCROLL: "root-scroll", CB_GET_ALL: "all"};
+const compile = (file: string) => transpileModule(readFileSync(join(__dirname, file), "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+const tabsSource = compile("MobileTabs.ts");
+const scrollSource = compile("../../protyle/scroll/saveScroll.ts");
+const layoutSource = compile("../util/saveLayout.ts");
+const clone = <T>(value: T): T => value === undefined ? value : JSON.parse(JSON.stringify(value));
+const entry = (id = "root", scrollTop = 100, notebookID = "box", rootID = "root") => ({
+ id, rootID, notebookID, path: `/${rootID}.sy`, title: id, action: [constants.CB_GET_SCROLL],
+ scroll: {rootId: rootID, startId: "start", endId: "end", scrollTop, zoomInId: id},
+});
+const tab = (id = "tab", current: any = entry()) => ({id, current, backStack: [] as any[], forwardStack: [] as any[], activeAt: 1});
+const saved = (tabs: any[] = [tab()], activeTabID = tabs[0]?.id) => ({version: 1, tabs, activeTabID});
+const flush = async () => { for (let index = 0; index < 30; index++) { await Promise.resolve(); } };
+
+type Load = {
+ id: string;
+ action: string[];
+ notebookID: string;
+ scroll: any;
+ success: (protyle: any) => void;
+ failure: (invalid?: boolean, editorUnchanged?: boolean) => void;
+ isValid: () => boolean;
+};
+
+const setup = (options: {
+ stored?: any;
+ readonly?: boolean;
+ publish?: boolean;
+ encrypted?: string[];
+ roots?: Record<string, string>;
+} = {}) => {
+ const writes: Array<{key: string, value: any}> = [];
+ const loads: Load[] = [];
+ const scrollCalls: boolean[] = [];
+ const toolbar = {value: ""};
+ let deferLoads = false;
+ let rejectWrite = false;
+ let sequence = 0;
+ const window: any = {siyuan: {storage: {mobileTabs: clone(options.stored), positions: {}},
+ config: {readonly: options.readonly, fileTree: {maxOpenTabCount: 32}}, isPublish: options.publish,
+ languages: {untitled: "Untitled", newTab: "New tab"}, mobile: {}, menus: {menu: {remove: () => {}}}}};
+ const document = {querySelector: (): null => null,
+ getElementById: (id: string) => id === "toolbarName" ? toolbar : null};
+ const rootFor = (id: string) => options.roots?.[id] || "root";
+ const makeProtyle = (load: Load) => ({
+ block: {rootID: rootFor(load.id), id: load.id, action: [...load.action], showAll: true},
+ notebookId: load.notebookID, path: `/${rootFor(load.id)}.sy`, element: {dataset: {}},
+ background: {ial: {icon: ""}}, toolbar: {},
+ contentElement: {scrollTop: load.scroll?.scrollTop ?? 0, getAttribute: (): null => null},
+ wysiwyg: {element: {firstElementChild: {getAttribute: () => "start"},
+ lastElementChild: {getAttribute: () => "end"}, contains: () => false}},
+ });
+ const complete = (load = loads.at(-1), install = true, bypassValidity = false) => {
+ if (!bypassValidity && !load.isValid()) {
+ return;
+ }
+ const protyle = makeProtyle(load);
+ if (install) {
+ window.siyuan.mobile.editor = {protyle};
+ toolbar.value = load.id;
+ }
+ load.success(protyle);
+ };
+ const setStorageVal = (key: string, value: unknown, callback?: () => void) => {
+ writes.push({key, value: clone(value)});
+ if (rejectWrite && key === constants.LOCAL_MOBILE_TABS) {
+ return Promise.reject(new Error("storage unavailable"));
+ }
+ callback?.();
+ return Promise.resolve();
+ };
+ const fetchPost = (_url: string, data: any, callback?: (response: any) => void) => {
+ callback?.({code: 0, data: {rootID: rootFor(data.id), box: data.notebook || "box"}});
+ return Promise.resolve();
+ };
+ const encrypted = (id: string) => options.encrypted?.includes(id) || false;
+ const common = {
+ "../../constants": {Constants: constants},
+ "../../util/pathName": {isEncryptedBox: encrypted},
+ "../../protyle/util/compatibility": {setStorageVal},
+ "../../util/fetch": {fetchPost},
+ };
+ const execute = (source: string, modules: Record<string, unknown>) => {
+ const api: any = {};
+ runInNewContext(source, {exports: api, require: (name: string) => modules[name] || {}, window, document,
+ AbortController, DOMException, getSelection: () => ({rangeCount: 0}), console: {warn: () => {}}});
+ return api;
+ };
+ const scrollApi = execute(scrollSource, {...common, "./scrollRequest": scrollRequest,
+ "../util/compatibility": {setStorageVal}});
+ const saveScroll = (protyle: any, getObject: boolean) => {
+ scrollCalls.push(getObject);
+ return scrollApi.saveScroll(protyle, getObject);
+ };
+ const layoutApi = execute(layoutSource, {...common, "../../protyle/scroll/saveScroll": {saveScroll},
+ "../../util/fetchTimeout": {withFetchTimeout: (task: () => Promise<boolean>) => task()}});
+ const tabsApi = execute(tabsSource, {...common, "./mobileTabsState": stateFunctions,
+ "../../util/genID": {genUUID: () => `new-${++sequence}`},
+ "../../protyle/scroll/saveScroll": {saveScroll}, "../util/saveLayout": layoutApi,
+ "../util/setEmpty": {setEmpty: () => { window.siyuan.mobile.editor = undefined; }},
+ "../util/closePanel": {closeModel: () => {}},
+ "../editor": {updateRecentDocSwitchTime: () => {}, loadMobileFileById: (_app: unknown, id: string,
+ action: string[], _position: unknown, notebookID: string, success: Load["success"],
+ _reload: boolean, isValid: Load["isValid"], _signal: unknown, scroll: any, _recent: boolean,
+ failure: Load["failure"]) => {
+ const load = {id, action, notebookID, success, isValid, scroll, failure};
+ loads.push(load);
+ if (!deferLoads) {
+ complete(load);
+ }
+ }},
+ });
+ tabsApi.MobileTabs.prototype.renderOverview = () => {};
+ tabsApi.MobileTabs.prototype.openOverview = () => {};
+ const tabs = new tabsApi.MobileTabs({});
+ window.siyuan.mobile.tabs = tabs;
+ return {tabs, window, writes, loads, scrollCalls, complete,
+ saveLayout: layoutApi.saveMobileLayout as () => Promise<boolean>,
+ get current(): any { return tabs.state.tabs.find((item: any) => item.id === tabs.state.activeTabID)?.current; },
+ get protyle(): any { return window.siyuan.mobile.editor?.protyle; },
+ set defer(value: boolean) { deferLoads = value; },
+ set reject(value: boolean) { rejectWrite = value; },
+ get persisted(): any { return writes.filter(write => write.key === constants.LOCAL_MOBILE_TABS).at(-1)?.value; },
+ };
+};
+
+test("layout save captures the live 8000 position and restores it after restart instead of stored 100", async () => {
+ const state = setup({stored: saved()});
+ await state.tabs.restore();
+ assert.equal(state.protyle.contentElement.scrollTop, 100);
+ state.protyle.contentElement.scrollTop = 8000;
+ const save = state.saveLayout();
+ state.protyle.contentElement.scrollTop = 9000;
+ assert.equal(await save, true);
+ assert.equal(state.persisted.tabs[0].current.scroll.scrollTop, 8000);
+ assert.ok(state.scrollCalls.every(Boolean), "tab snapshots use saveScroll's object-only path");
+ assert.deepEqual(clone(state.window.siyuan.storage.positions), {});
+ const restarted = setup({stored: state.persisted});
+ await restarted.tabs.restore();
+ assert.equal(restarted.loads[0].scroll.scrollTop, 8000);
+ assert.equal(restarted.protyle.contentElement.scrollTop, 8000);
+});
+
+test("two tabs for the same document keep independent positions across switches and restart", async () => {
+ const state = setup({stored: saved([tab("first", entry("first-block", 100)), tab("second", entry("second-block", 200))])});
+ await state.tabs.restore();
+ state.protyle.contentElement.scrollTop = 8000;
+ await state.tabs.switchTo("second");
+ assert.equal(state.protyle.contentElement.scrollTop, 200);
+ state.protyle.contentElement.scrollTop = 9000;
+ await state.tabs.save();
+ assert.deepEqual(state.persisted.tabs.map((item: any) => item.current.scroll.scrollTop), [8000, 9000]);
+ await state.tabs.switchTo("first");
+ assert.equal(state.protyle.contentElement.scrollTop, 8000);
+ await state.tabs.save();
+ const restarted = setup({stored: state.persisted});
+ await restarted.tabs.restore();
+ assert.equal(restarted.protyle.contentElement.scrollTop, 8000);
+ await restarted.tabs.switchTo("second");
+ assert.equal(restarted.protyle.contentElement.scrollTop, 9000);
+});
+
+test("same-root back and forward targets are never overwritten by the still-rendered history entry", async () => {
+ const state = setup({stored: saved([tab("tab", entry("first-block", 100))])});
+ await state.tabs.restore();
+ await state.tabs.open("second-block", {tabID: "tab"});
+ state.protyle.contentElement.scrollTop = 8000;
+ state.defer = true;
+ const back = state.tabs.goBack();
+ await flush();
+ assert.equal(state.loads.at(-1).scroll.scrollTop, 100);
+ await state.tabs.save();
+ assert.equal(state.persisted.tabs[0].current.scroll.scrollTop, 100);
+ assert.equal(state.persisted.tabs[0].forwardStack[0].scroll.scrollTop, 8000);
+ state.complete();
+ await back;
+ const forward = state.tabs.goForward();
+ await flush();
+ assert.equal(state.loads.at(-1).scroll.scrollTop, 8000);
+ await state.tabs.save();
+ assert.equal(state.persisted.tabs[0].current.scroll.scrollTop, 8000);
+ state.complete();
+ await forward;
+ assert.equal(state.protyle.contentElement.scrollTop, 8000);
+});
+
+test("saving before restore does not treat an unrelated editor with the same root as the active tab", async () => {
+ const state = setup({stored: saved()});
+ state.window.siyuan.mobile.editor = {protyle: {block: {rootID: "root"}, notebookId: "box"}};
+ assert.equal(await state.tabs.save(), true);
+ assert.equal(state.persisted.tabs[0].current.scroll.scrollTop, 100);
+ assert.equal(state.scrollCalls.length, 0);
+});
+
+test("a notebook mismatch cannot overwrite an owned entry even when the root ID matches", async () => {
+ const state = setup({stored: saved()});
+ await state.tabs.restore();
+ state.protyle.notebookId = "other-box";
+ state.protyle.contentElement.scrollTop = 8000;
+ await state.tabs.save();
+ assert.equal(state.persisted.tabs[0].current.notebookID, "box");
+ assert.equal(state.persisted.tabs[0].current.scroll.scrollTop, 100);
+});
+
+test("partially loaded editor content stays unowned after failure until a successful restoration", async () => {
+ const state = setup({stored: saved()});
+ await state.tabs.restore();
+ state.protyle.contentElement.scrollTop = 200;
+ state.defer = true;
+ const opening = state.tabs.open("partial", {tabID: "tab"});
+ await flush();
+ state.protyle.block.id = "partial";
+ state.protyle.contentElement.scrollTop = 8000;
+ await state.tabs.save();
+ assert.equal(state.persisted.tabs[0].current.id, "root");
+ assert.equal(state.persisted.tabs[0].current.scroll.scrollTop, 200);
+ state.loads.at(-1).failure(false, false);
+ assert.equal(await opening, "failed");
+ await state.tabs.save();
+ assert.equal(state.persisted.tabs[0].current.scroll.scrollTop, 200);
+ state.defer = false;
+ await state.tabs.restore();
+ state.protyle.contentElement.scrollTop = 9000;
+ await state.tabs.save();
+ assert.equal(state.persisted.tabs[0].current.scroll.scrollTop, 9000);
+});
+
+test("an early load failure preserves ownership of the unchanged editor for later saves", async () => {
+ const state = setup({stored: saved()});
+ await state.tabs.restore();
+ state.protyle.contentElement.scrollTop = 200;
+ state.defer = true;
+ const opening = state.tabs.open("unavailable", {tabID: "tab"});
+ await flush();
+ state.loads.at(-1).failure(false, true);
+ assert.equal(await opening, "failed");
+ state.protyle.contentElement.scrollTop = 8000;
+ await state.tabs.save();
+ assert.equal(state.persisted.tabs[0].current.id, "root");
+ assert.equal(state.persisted.tabs[0].current.scroll.scrollTop, 8000);
+});
+
+test("a stale early failure cannot reclaim ownership from a successful newer navigation", async () => {
+ const state = setup({stored: saved()});
+ await state.tabs.restore();
+ state.defer = true;
+ const stale = state.tabs.open("stale", {tabID: "tab"});
+ await flush();
+ const staleLoad = state.loads.at(-1);
+ const latest = state.tabs.open("latest", {tabID: "tab"});
+ await flush();
+ assert.equal(await stale, "cancelled");
+ state.complete();
+ assert.equal(await latest, "success");
+ const ownedEntry = state.current;
+ staleLoad.failure(false, true);
+ assert.equal(state.tabs.renderedEntry, ownedEntry);
+ state.protyle.contentElement.scrollTop = 8000;
+ await state.tabs.save();
+ assert.equal(state.persisted.tabs[0].current.id, "latest");
+ assert.equal(state.persisted.tabs[0].current.scroll.scrollTop, 8000);
+});
+
+test("an unchanged-editor failure flag cannot claim a replacement editor with the same document", async () => {
+ const state = setup({stored: saved()});
+ await state.tabs.restore();
+ state.protyle.contentElement.scrollTop = 200;
+ state.defer = true;
+ const opening = state.tabs.open("unavailable", {tabID: "tab"});
+ await flush();
+ state.window.siyuan.mobile.editor = {protyle: {...state.protyle,
+ contentElement: {...state.protyle.contentElement, scrollTop: 8000}}};
+ state.loads.at(-1).failure(false, true);
+ assert.equal(await opening, "failed");
+ await state.tabs.save();
+ assert.equal(state.persisted.tabs[0].current.scroll.scrollTop, 200);
+});
+
+test("a forced stale success callback cannot reclaim ownership after a newer same-root navigation", async () => {
+ const state = setup({stored: saved()});
+ await state.tabs.restore();
+ state.defer = true;
+ const stale = state.tabs.open("stale", {tabID: "tab"});
+ await flush();
+ const staleLoad = state.loads.at(-1);
+ const latest = state.tabs.open("latest", {tabID: "tab"});
+ await flush();
+ assert.equal(await stale, "cancelled");
+ assert.equal(staleLoad.isValid(), false);
+ state.complete();
+ assert.equal(await latest, "success");
+ const ownedEntry = state.current;
+ state.complete(staleLoad, false, true);
+ assert.equal(state.current, ownedEntry);
+ assert.equal(state.tabs.renderedEntry, ownedEntry);
+ state.protyle.contentElement.scrollTop = 8000;
+ await state.tabs.save();
+ assert.equal(state.persisted.tabs[0].current.id, "latest");
+ assert.equal(state.persisted.tabs[0].current.scroll.scrollTop, 8000);
+});
+
+test("a pending encrypted-to-plain load cannot relabel and persist the encrypted editor", async () => {
+ const state = setup({encrypted: ["secret"]});
+ await state.tabs.open("secret-block", {notebookId: "secret"});
+ state.protyle.contentElement.scrollTop = 8000;
+ const activeID = state.tabs.state.activeTabID;
+ state.defer = true;
+ const opening = state.tabs.open("plain-block", {notebookId: "box", tabID: activeID});
+ await flush();
+ state.protyle.notebookId = "box";
+ await state.tabs.save();
+ assert.equal(state.current.notebookID, "secret");
+ assert.equal(state.persisted.tabs[0].current, undefined);
+ assert.equal(JSON.stringify(state.persisted).includes("secret-block"), false);
+ state.complete();
+ assert.equal(await opening, "success");
+ await state.tabs.save();
+ assert.equal(state.persisted.tabs[0].current.id, "plain-block");
+ assert.deepEqual(state.persisted.tabs[0].backStack, []);
+ assert.deepEqual(clone(state.window.siyuan.storage.positions), {});
+});
+
+test("encrypted current and history entries are filtered from every saved tab", async () => {
+ const state = setup({stored: saved(), encrypted: ["secret"]});
+ await state.tabs.restore();
+ const active = state.tabs.state.tabs[0];
+ active.backStack = [entry("public-back"), entry("secret-back", 1, "secret")];
+ active.forwardStack = [entry("secret-forward", 2, "secret"), entry("public-forward")];
+ state.tabs.state.tabs.push(tab("secret-tab", entry("secret-current", 3, "secret")));
+ await state.tabs.save();
+ assert.deepEqual(state.persisted.tabs[0].backStack.map((item: any) => item.id), ["public-back"]);
+ assert.deepEqual(state.persisted.tabs[0].forwardStack.map((item: any) => item.id), ["public-forward"]);
+ assert.equal(state.persisted.tabs[1].current, undefined);
+ assert.equal(JSON.stringify(state.persisted).includes("secret-current"), false);
+});
+
+test("blank or readonly scroll snapshots preserve the last valid saved position", async () => {
+ for (const readonly of [false, true]) {
+ const state = setup({stored: saved()});
+ await state.tabs.restore();
+ await flush();
+ state.writes.length = 0;
+ state.protyle.contentElement.scrollTop = 8000;
+ if (readonly) {
+ state.window.siyuan.config.readonly = true;
+ } else {
+ state.protyle.wysiwyg.element.firstElementChild = null;
+ }
+ assert.equal(await state.tabs.save(), true);
+ assert.equal(state.current.scroll.scrollTop, 100);
+ if (readonly) {
+ assert.equal(state.writes.length, 0);
+ } else {
+ assert.equal(state.persisted.tabs[0].current.scroll.scrollTop, 100);
+ }
+ }
+});
+
+test("legacy migration saves no temporary empty session and explicit blank sessions remain persistent", async () => {
+ for (const stored of [undefined, {version: 2, tabs: [] as unknown[]}, {version: 1, tabs: null}]) {
+ const state = setup({stored});
+ assert.equal(await state.tabs.save(), true);
+ assert.equal(state.writes.length, 0);
+ assert.equal(state.tabs.canRestoreLegacyDocument(), true);
+ state.tabs.createBlank();
+ assert.equal(await state.tabs.save(), true);
+ assert.equal(state.persisted.tabs.length, 1);
+ assert.equal(state.persisted.tabs[0].current, undefined);
+ }
+});
+
+test("a failed write is reported and a later save retries with the latest live position", async () => {
+ const state = setup({stored: saved()});
+ await state.tabs.restore();
+ await flush();
+ state.reject = true;
+ state.protyle.contentElement.scrollTop = 8000;
+ assert.equal(await state.tabs.save(), false);
+ assert.equal(state.persisted.tabs[0].current.scroll.scrollTop, 8000);
+ state.reject = false;
+ state.protyle.contentElement.scrollTop = 9000;
+ assert.equal(await state.tabs.save(), true);
+ assert.equal(state.persisted.tabs[0].current.scroll.scrollTop, 9000);
+});
+
+test("saving a closed session cannot revive the last rendered document", async () => {
+ const state = setup({stored: saved()});
+ await state.tabs.restore();
+ state.protyle.contentElement.scrollTop = 8000;
+ state.tabs.closeAll();
+ assert.equal(await state.tabs.save(), true);
+ assert.deepEqual(state.persisted.tabs, []);
+ assert.equal(state.persisted.activeTabID, undefined);
+});
diff --git a/app/src/mobile/tabs/MobileTabs.startup.test.ts b/app/src/mobile/tabs/MobileTabs.startup.test.ts
index 4e2b40f466..b3bf6ec912 100644
--- a/app/src/mobile/tabs/MobileTabs.startup.test.ts
+++ b/app/src/mobile/tabs/MobileTabs.startup.test.ts
@@ -67,6 +67,10 @@ const setup = (storage: Record<string, any> = {}, options: {
writes.push({key, value: clone(value)});
return Promise.resolve();
}},
+ "../util/saveLayout": {saveMobileStorage: (key: string, value: unknown) => {
+ writes.push({key, value: clone(value)});
+ return Promise.resolve(true);
+ }},
"../../util/pathName": {isEncryptedBox: (id: string) => options.encrypted?.includes(id)},
"../../util/genID": {genUUID: () => `new-${++sequence}`},
"../../protyle/scroll/saveScroll": {saveScroll: (): undefined => undefined},
diff --git a/app/src/mobile/tabs/MobileTabs.ts b/app/src/mobile/tabs/MobileTabs.ts
index 5622978844..cd4ab815db 100644
--- a/app/src/mobile/tabs/MobileTabs.ts
+++ b/app/src/mobile/tabs/MobileTabs.ts
@@ -13,6 +13,7 @@ import {loadMobileFileById, updateRecentDocSwitchTime} from "../editor";
import {openModel} from "../menu/model";
import {closeModel} from "../util/closePanel";
import {setEmpty} from "../util/setEmpty";
+import {saveMobileStorage} from "../util/saveLayout";
import {canCloseTab, moveTab, orderTabsForOverview, toggleTabPin, trimTabsToLimit} from "./mobileTabsState";
const MAX_HISTORY = 32;
@@ -124,6 +125,7 @@ export class MobileTabs {
private state: MobileTabsState;
private hasStoredTabs: boolean;
private navigationEpoch = 0;
+ private renderedEntry?: MobileTabEntry;
private abortController?: AbortController;
private activationBackStack: string[] = [];
private activationForwardStack: string[] = [];
@@ -207,8 +209,9 @@ export class MobileTabs {
activationForwardStack: this.activationForwardStack,
};
window.siyuan.storage[Constants.LOCAL_MOBILE_TABS] = persistedState;
- setStorageVal(Constants.LOCAL_MOBILE_TABS, persistedState);
+ const saved = saveMobileStorage(Constants.LOCAL_MOBILE_TABS, persistedState);
this.updateNavigationButtons();
+ return saved;
}
private updateCounter() {
@@ -230,12 +233,16 @@ export class MobileTabs {
}
private snapshot(tab = this.activeTab) {
- if (!tab?.current || !window.siyuan.mobile.editor?.protyle) {
+ if (!tab?.current || tab.current !== this.renderedEntry || !window.siyuan.mobile.editor?.protyle) {
return;
}
const protyle = window.siyuan.mobile.editor.protyle;
- if (protyle.block.rootID === tab.current.rootID) {
- tab.current.scroll = saveScroll(protyle, true) as IScrollAttr | undefined;
+ if (protyle.block.rootID === tab.current.rootID && protyle.notebookId === tab.current.notebookID) {
+ const scroll = saveScroll(protyle, true) as IScrollAttr | undefined;
+ if (!scroll) {
+ return;
+ }
+ tab.current.scroll = scroll;
tab.current.title = (document.getElementById("toolbarName") as HTMLInputElement)?.value || tab.current.title;
tab.current.id = protyle.block.showAll ? protyle.block.id : protyle.block.rootID;
tab.current.notebookID = protyle.notebookId;
@@ -416,6 +423,10 @@ export class MobileTabs {
};
abortController.signal.addEventListener("abort", () => finish("cancelled"), {once: true});
// 过期响应由 epoch 和 isValid 丢弃,不向 fetch 传递 signal。
+ // 共享编辑器加载期间不属于任何页签,不能把中间状态保存到原页签。
+ const renderedEntry = this.renderedEntry;
+ const renderedProtyle = window.siyuan.mobile.editor?.protyle;
+ this.renderedEntry = undefined;
loadMobileFileById(this.app, loadID, loadAction, options.scrollPosition, info.box, (protyle) => {
if (epoch !== this.navigationEpoch) {
finish("cancelled");
@@ -433,6 +444,7 @@ export class MobileTabs {
this.state.tabs.push(tab);
}
tab.current = this.entryFromProtyle(loadID, loadAction, protyle);
+ this.renderedEntry = tab.current;
tab.activeAt = Date.now();
if (options.recordActivation !== false && activeBefore?.id !== tab.id) {
this.recordActivation(activeBefore?.id);
@@ -458,7 +470,12 @@ export class MobileTabs {
}
finish("success");
options.afterOpen?.(protyle);
- }, options.forceReload, () => epoch === this.navigationEpoch, undefined, loadScroll, false, (invalid) => {
+ }, options.forceReload, () => epoch === this.navigationEpoch, undefined, loadScroll, false, (invalid, editorUnchanged) => {
+ // 加载尚未修改编辑器时恢复原页签归属,允许用户继续阅读和保存。
+ if (editorUnchanged && epoch === this.navigationEpoch && this.activeTab?.current === renderedEntry &&
+ window.siyuan.mobile.editor?.protyle === renderedProtyle) {
+ this.renderedEntry = renderedEntry;
+ }
finish(abortController.signal.aborted ? "cancelled" : (invalid ? "invalid" : "failed"));
}, options.keepPanels);
});
@@ -793,13 +810,13 @@ export class MobileTabs {
this.updateCounter();
}
- save() {
+ async save(): Promise<boolean> {
this.snapshot();
// 尚未迁移成功的临时空状态不能在关闭页面时覆盖旧版恢复记录。
if (!this.hasStoredTabs && this.state.tabs.length === 0) {
- return;
+ return true;
}
- this.persist();
+ return this.persist();
}
pushCurrent() {
diff --git a/app/src/mobile/util/saveLayout.integration.test.ts b/app/src/mobile/util/saveLayout.integration.test.ts
new file mode 100644
index 0000000000..123934c996
--- /dev/null
+++ b/app/src/mobile/util/saveLayout.integration.test.ts
@@ -0,0 +1,156 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import test from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, forEachChild, isCallExpression, isVariableDeclaration, isVariableStatement, ScriptTarget, transpileModule} from "typescript";
+
+const {parse} = require("ifdef-loader/preprocessor");
+const readSource = (file: string, mobile = true) => createSourceFile(file,
+ parse(readFileSync(join(__dirname, "../../", file), "utf8"), {MOBILE: mobile, BROWSER: true}, false, true),
+ ScriptTarget.ES2021, true);
+const loadFunction = (file: string, name: string, dependencies: Record<string, unknown>, mobile = true) => {
+ const source = readSource(file, mobile);
+ const declaration = source.statements.filter(isVariableStatement).flatMap(item => Array.from(item.declarationList.declarations))
+ .find(item => item.name.getText(source) === name);
+ assert.ok(declaration, name);
+ const code = transpileModule(`const target = ${declaration.initializer.getText(source)};`, {
+ compilerOptions: {target: ScriptTarget.ES2021},
+ }).outputText;
+ return runInNewContext(code + "\ntarget;", dependencies);
+};
+const deferred = () => {
+ let resolve: (value: boolean) => void;
+ const promise = new Promise<boolean>(done => { resolve = done; });
+ return {promise, resolve};
+};
+const flush = async () => { await Promise.resolve(); await Promise.resolve(); };
+
+test("mobile plugin saveLayout completes the callback only after a successful save", async () => {
+ for (const succeeds of [true, false]) {
+ const pending = deferred();
+ let called = 0;
+ let errors = 0;
+ const save = loadFunction("plugin/API.ts", "saveLayout", {
+ saveMobileLayout: () => pending.promise,
+ window: {siyuan: {languages: {mobileLayoutSaveError: "Save failed"}}},
+ showMessage: () => { errors++; },
+ });
+ save(() => { called++; });
+ assert.equal(called, 0);
+ pending.resolve(succeeds);
+ await flush();
+ assert.equal(called, succeeds ? 1 : 0);
+ assert.equal(errors, succeeds ? 0 : 1);
+ }
+});
+
+test("desktop plugin saveLayout retains exportLayout", () => {
+ const calls: any[] = [];
+ const callback = () => {};
+ const save = loadFunction("plugin/API.ts", "saveLayout", {exportLayout: (options: unknown) => calls.push(options)}, false);
+ save(callback);
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].cb, callback);
+ assert.equal(calls[0].errorExit, false);
+});
+
+test("mobile normal exit waits for save and remains open on failure", async () => {
+ for (const ownsKernel of [true, false]) {
+ for (const succeeds of [true, false]) {
+ const pending = deferred();
+ const events: string[] = [];
+ const exit = loadFunction("dialog/processSystem.ts", "exitSiYuan", {
+ getSettingsWindowHost: (): undefined => undefined,
+ hideAllElements: () => {},
+ saveMobileLayout: () => pending.promise,
+ getHostCapabilities: () => ({ownsKernel}),
+ forceQuit: () => events.push("quit"),
+ fetchPost: (url: string) => events.push(url),
+ showMessage: () => events.push("error"),
+ window: {siyuan: {languages: {mobileLayoutSaveError: "Save failed"}}},
+ });
+ const exiting = exit();
+ assert.deepEqual(events, []);
+ pending.resolve(succeeds);
+ await exiting;
+ assert.deepEqual(events, succeeds ? [ownsKernel ? "/api/system/exit" : "quit"] : ["error"]);
+ }
+ }
+});
+
+test("mobile lock screen logs out after save completion even when saving fails", async () => {
+ for (const succeeds of [true, false]) {
+ const pending = deferred();
+ const events: string[] = [];
+ const lock = loadFunction("dialog/processSystem.ts", "lockScreen", {
+ window: {siyuan: {config: {readonly: false}}},
+ emitToPlugins: () => events.push("lock"),
+ saveMobileLayout: () => pending.promise,
+ fetchPost: (url: string) => events.push(url),
+ });
+ const locking = lock();
+ assert.deepEqual(events, ["lock"]);
+ pending.resolve(succeeds);
+ await locking;
+ assert.deepEqual(events, ["lock", "/api/system/logoutAuth"]);
+ }
+});
+
+test("hidden, pagehide and beforeunload use the unified mobile save entry", () => {
+ const source = readSource("mobile/index.ts");
+ const registrations: string[] = [];
+ const findListeners = (node: import("typescript").Node) => {
+ if (isCallExpression(node) && ["window.addEventListener", "document.addEventListener"].includes(node.expression.getText(source)) &&
+ ["\"beforeunload\"", "\"pagehide\"", "\"visibilitychange\""].includes(node.arguments[0]?.getText(source))) {
+ registrations.push(node.getText(source));
+ }
+ forEachChild(node, findListeners);
+ };
+ findListeners(source);
+ assert.equal(registrations.length, 3);
+ const handlers = new Map<string, () => void>();
+ let saves = 0;
+ const document = {visibilityState: "visible", addEventListener: (name: string, handler: () => void) => handlers.set(name, handler)};
+ runInNewContext(transpileModule(registrations.join(";\n"), {
+ compilerOptions: {target: ScriptTarget.ES2021},
+ }).outputText, {
+ window: {addEventListener: document.addEventListener}, document,
+ saveMobileLayout: () => { saves++; return Promise.resolve(true); },
+ });
+ handlers.get("visibilitychange")();
+ assert.equal(saves, 0);
+ document.visibilityState = "hidden";
+ handlers.get("visibilitychange")();
+ handlers.get("pagehide")();
+ handlers.get("beforeunload")();
+ assert.equal(saves, 3);
+});
+
+test("mobile loader distinguishes early failures from a partially changed editor", () => {
+ const source = readSource("mobile/editor.ts");
+ let failSource: string;
+ const visit = (node: import("typescript").Node) => {
+ if (isVariableDeclaration(node) && node.name.getText(source) === "fail") {
+ failSource = node.initializer.getText(source);
+ }
+ forEachChild(node, visit);
+ };
+ visit(source);
+ assert.ok(failSource);
+ for (const titleHidden of [false, true]) {
+ const failures: unknown[][] = [];
+ let shown = 0;
+ runInNewContext(transpileModule(`let completed = false; const fail = ${failSource}; fail(true); fail();`, {
+ compilerOptions: {target: ScriptTarget.ES2021},
+ }).outputText, {
+ titleHidden,
+ isValid: () => true,
+ window: {siyuan: {mobile: {editor: {protyle: {wysiwyg: {element: {childElementCount: 1}}}}}}},
+ setEditor: () => { shown++; },
+ onFailure: (...args: unknown[]) => failures.push(args),
+ });
+ assert.deepEqual(failures, [[true, !titleHidden]]);
+ assert.equal(shown, titleHidden ? 1 : 0);
+ }
+});
diff --git a/app/src/mobile/util/saveLayout.test.ts b/app/src/mobile/util/saveLayout.test.ts
new file mode 100644
index 0000000000..1bc47c0685
--- /dev/null
+++ b/app/src/mobile/util/saveLayout.test.ts
@@ -0,0 +1,401 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {test} from "node:test";
+import {setImmediate} from "node:timers";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const constants = {LOCAL_MOBILE_TABS: "local-mobile-tabs", LOCAL_FILEPOSITION: "local-fileposition"};
+const source = (path: string) => transpileModule(readFileSync(join(__dirname, path), "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},
+}).outputText;
+const layoutSource = source("saveLayout.ts");
+const timeoutSource = source("../../util/fetchTimeout.ts");
+const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
+const flush = () => new Promise<void>(resolve => setImmediate(resolve));
+
+type StorageRequest = {
+ key: string;
+ value: unknown;
+ callback: () => void;
+ timeout: number;
+ resolve: () => void;
+ reject: (error: Error) => void;
+ signal?: AbortSignal;
+};
+
+const loadLayout = (timedRequests = false) => {
+ let now = 0;
+ let timerID = 0;
+ const timers = new Map<number, {at: number, callback: () => void}>();
+ const timeoutAPI = {} as typeof import("../../util/fetchTimeout");
+ runInNewContext(timeoutSource, {
+ exports: timeoutAPI,
+ AbortController,
+ DOMException,
+ setTimeout: (callback: () => void, delay: number) => {
+ timers.set(++timerID, {at: now + delay, callback});
+ return timerID;
+ },
+ clearTimeout: (id: number) => timers.delete(id),
+ });
+ const requests: StorageRequest[] = [];
+ const warnings: unknown[][] = [];
+ const scrollCalls: {protyle: IProtyle, force: boolean}[] = [];
+ const state = {
+ config: {readonly: false},
+ isPublish: false,
+ mobile: {} as {tabs?: {save: () => Promise<boolean>}, editor?: {protyle: IProtyle}},
+ storage: {[constants.LOCAL_FILEPOSITION]: {} as Record<string, unknown>},
+ };
+ const controls = {
+ scroll: {id: "visible-block", top: 42} as unknown,
+ storageError: undefined as Error | undefined,
+ };
+ const api = {} as typeof import("./saveLayout");
+ const modules: Record<string, unknown> = {
+ "../../constants": {Constants: constants},
+ "../../protyle/scroll/saveScroll": {saveScroll: (protyle: IProtyle, force: boolean) => {
+ scrollCalls.push({protyle, force});
+ return controls.scroll;
+ }},
+ "../../protyle/util/compatibility": {setStorageVal: (
+ key: string, value: unknown, callback: () => void, timeout: number,
+ ) => {
+ if (controls.storageError) {
+ throw controls.storageError;
+ }
+ let resolve: () => void;
+ let reject: (error: Error) => void;
+ const promise = new Promise<void>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ const request = {key, value, callback, timeout, resolve, reject} as StorageRequest;
+ requests.push(request);
+ return timedRequests ? timeoutAPI.withFetchTimeout((signal) => {
+ request.signal = signal;
+ return promise;
+ }, undefined, timeout).catch(() => {}) : promise;
+ }},
+ "../../util/pathName": {isEncryptedBox: (id: string) => id === "encrypted-box"},
+ "../../util/fetchTimeout": timeoutAPI,
+ };
+ runInNewContext(layoutSource, {
+ exports: api,
+ require: (name: string) => {
+ assert.ok(name in modules, name);
+ return modules[name];
+ },
+ window: {siyuan: state},
+ console: {warn: (...args: unknown[]) => warnings.push(args)},
+ });
+ const advance = async (milliseconds: number) => {
+ const end = now + milliseconds;
+ await flush();
+ while (true) {
+ const next = Array.from(timers.entries()).filter(([, timer]) => timer.at <= end)
+ .sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
+ if (!next) {
+ break;
+ }
+ now = next[1].at;
+ timers.delete(next[0]);
+ next[1].callback();
+ await flush();
+ }
+ now = end;
+ };
+ return {api, state, controls, requests, warnings, scrollCalls, timers, advance};
+};
+
+const succeed = (request: StorageRequest) => {
+ request.callback();
+ request.resolve();
+};
+const editor = (notebookId = "public-box") => ({
+ protyle: {notebookId, block: {rootID: "document"}} as IProtyle,
+});
+const entry = (id: string) => ({
+ id, rootID: id, notebookID: "public-box", path: `/${id}.sy`, title: id,
+ action: ["cb-get-scroll"], scroll: {id: `${id}-block`, top: 10},
+});
+const tabsState = () => ({
+ version: 1,
+ activeTabID: "tab-1",
+ tabs: [{id: "tab-1", current: entry("current"), backStack: [entry("back")],
+ forwardStack: [entry("forward")], activeAt: 100}],
+ activationBackStack: ["tab-2"],
+ activationForwardStack: ["tab-3"],
+});
+
+test("mobile storage snapshots nested tab data synchronously and writes snapshots in FIFO order", async () => {
+ const {api, requests} = loadLayout();
+ const state = tabsState();
+ const firstSnapshot = clone(state);
+ const first = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, state);
+ state.tabs[0].current.action.push("cb-get-focus");
+ state.tabs[0].current.scroll.top = 20;
+ state.tabs[0].backStack[0].action.push("cb-get-focus");
+ state.tabs[0].backStack[0].scroll.top = 30;
+ state.tabs[0].forwardStack[0].scroll.top = 40;
+ state.activationBackStack.push("tab-4");
+ state.activationForwardStack.splice(0, 1);
+ const secondSnapshot = clone(state);
+ const second = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, state);
+ state.tabs[0].current.action.length = 0;
+ state.tabs[0].backStack.length = 0;
+ state.tabs[0].forwardStack[0].action.length = 0;
+ state.tabs[0].forwardStack.length = 0;
+ state.tabs[0].current.scroll.top = 90;
+ state.activationBackStack.length = 0;
+ state.activationForwardStack.push("tab-5");
+ const thirdSnapshot = clone(state);
+ const third = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, state);
+ state.tabs.length = 0;
+ state.activationForwardStack.length = 0;
+ assert.equal(requests.length, 1);
+ assert.deepEqual(clone(requests[0].value), firstSnapshot);
+ succeed(requests[0]);
+ assert.equal(await first, true);
+ await flush();
+ assert.equal(requests.length, 2);
+ assert.deepEqual(clone(requests[1].value), secondSnapshot);
+ succeed(requests[1]);
+ assert.equal(await second, true);
+ await flush();
+ assert.equal(requests.length, 3);
+ assert.deepEqual(clone(requests[2].value), thirdSnapshot);
+ succeed(requests[2]);
+ assert.equal(await third, true);
+ assert.ok(requests.every(request => request.timeout === 10000));
+});
+
+test("a success callback does not settle storage or release its queue before the request settles", async () => {
+ const {api, requests} = loadLayout();
+ let settled = false;
+ const first = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, {revision: 1});
+ void first.then(() => { settled = true; });
+ const second = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, {revision: 2});
+ requests[0].callback();
+ await flush();
+ assert.equal(settled, false);
+ assert.equal(requests.length, 1);
+ requests[0].resolve();
+ assert.equal(await first, true);
+ await flush();
+ assert.equal(requests.length, 2);
+ succeed(requests[1]);
+ assert.equal(await second, true);
+});
+
+test("a consumed request failure reports false and does not block the next snapshot", async () => {
+ const {api, requests} = loadLayout();
+ const first = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, {revision: 1});
+ const second = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, {revision: 2});
+ requests[0].resolve();
+ assert.equal(await first, false);
+ requests[0].callback();
+ assert.equal(await first, false);
+ await flush();
+ assert.equal(requests.length, 2);
+ succeed(requests[1]);
+ assert.equal(await second, true);
+});
+
+test("a rejected request reports false and does not poison the tab storage queue", async () => {
+ const {api, requests, warnings} = loadLayout();
+ const first = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, {revision: 1});
+ const second = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, {revision: 2});
+ requests[0].reject(new Error("offline"));
+ assert.equal(await first, false);
+ assert.equal(warnings.length, 1);
+ await flush();
+ succeed(requests[1]);
+ assert.equal(await second, true);
+});
+
+test("a storage callback followed by request rejection still reports failure", async () => {
+ const {api, requests} = loadLayout();
+ const saving = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, {});
+ requests[0].callback();
+ requests[0].reject(new Error("response processing failed"));
+ assert.equal(await saving, false);
+});
+
+test("a synchronous storage exception reports failure and permits a later save", async () => {
+ const {api, requests, controls} = loadLayout();
+ controls.storageError = new Error("request setup failed");
+ assert.equal(await api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, {}), false);
+ controls.storageError = undefined;
+ const saving = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, {revision: 2});
+ await flush();
+ assert.equal(requests.length, 1);
+ succeed(requests[0]);
+ assert.equal(await saving, true);
+});
+
+test("legacy position writes start immediately even while tab and position writes are pending", async () => {
+ const {api, requests} = loadLayout();
+ const first = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, {revision: 1});
+ const second = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, {revision: 2});
+ const positions = {document: {id: "block", top: 10}};
+ const legacyFirst = api.saveMobileStorage(constants.LOCAL_FILEPOSITION, positions);
+ positions.document.top = 20;
+ const legacySecond = api.saveMobileStorage(constants.LOCAL_FILEPOSITION, positions);
+ positions.document.top = 30;
+ assert.deepEqual(requests.map(request => request.key), [
+ constants.LOCAL_MOBILE_TABS, constants.LOCAL_FILEPOSITION, constants.LOCAL_FILEPOSITION,
+ ]);
+ assert.deepEqual(clone(requests[1].value), {document: {id: "block", top: 10}});
+ assert.deepEqual(clone(requests[2].value), {document: {id: "block", top: 20}});
+ requests.forEach(succeed);
+ assert.deepEqual(await Promise.all([first, legacyFirst, legacySecond]), [true, true, true]);
+ await flush();
+ assert.equal(requests.length, 4);
+ succeed(requests[3]);
+ assert.equal(await second, true);
+});
+
+test("readonly and published storage saves succeed without cloning or sending data", async () => {
+ for (const mode of ["readonly", "publish"]) {
+ const {api, state, requests} = loadLayout();
+ state.config.readonly = mode === "readonly";
+ state.isPublish = mode === "publish";
+ const circular: {self?: unknown} = {};
+ circular.self = circular;
+ assert.equal(await api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, circular), true);
+ assert.equal(await api.saveMobileStorage(constants.LOCAL_FILEPOSITION, circular), true);
+ assert.equal(requests.length, 0);
+ }
+});
+
+test("layout save calls the tab saver synchronously and awaits its result", async () => {
+ const {api, state, requests, scrollCalls, timers} = loadLayout();
+ const snapshot = tabsState();
+ state.mobile.editor = editor();
+ let calls = 0;
+ state.mobile.tabs = {save: () => {
+ calls++;
+ return api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, snapshot);
+ }};
+ const saving = api.saveMobileLayout();
+ assert.equal(calls, 1);
+ assert.equal(requests.length, 1);
+ snapshot.tabs[0].current.scroll.top = 99;
+ assert.equal((clone(requests[0].value) as typeof snapshot).tabs[0].current.scroll.top, 10);
+ assert.equal(scrollCalls.length, 0);
+ succeed(requests[0]);
+ assert.equal(await saving, true);
+ assert.equal(timers.size, 0);
+});
+
+test("layout save preserves a false tab result and converts thrown or rejected tab saves to false", async () => {
+ for (const failure of ["false", "throw", "reject"]) {
+ const {api, state, timers} = loadLayout();
+ state.mobile.tabs = {save: () => {
+ if (failure === "throw") {
+ throw new Error("snapshot failed");
+ }
+ return failure === "reject" ? Promise.reject(new Error("save failed")) : Promise.resolve(false);
+ }};
+ assert.equal(await api.saveMobileLayout(), false);
+ assert.equal(timers.size, 0);
+ }
+});
+
+test("blank layouts and editors without a scroll snapshot need no storage write", async () => {
+ const {api, state, controls, requests, scrollCalls} = loadLayout();
+ assert.equal(await api.saveMobileLayout(), true);
+ assert.equal(scrollCalls.length, 0);
+ state.mobile.editor = editor();
+ controls.scroll = undefined;
+ assert.equal(await api.saveMobileLayout(), true);
+ assert.equal(scrollCalls.length, 1);
+ assert.equal(requests.length, 0);
+});
+
+test("legacy layout capture saves the current scroll synchronously and preserves other positions", async () => {
+ const {api, state, controls, requests, scrollCalls} = loadLayout();
+ state.mobile.editor = editor();
+ state.storage[constants.LOCAL_FILEPOSITION].other = {id: "other-block", top: 15};
+ const saving = api.saveMobileLayout();
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0].key, constants.LOCAL_FILEPOSITION);
+ assert.equal(scrollCalls[0].protyle, state.mobile.editor.protyle);
+ assert.equal(scrollCalls[0].force, true);
+ assert.deepEqual(clone(requests[0].value), {
+ document: {id: "visible-block", top: 42}, other: {id: "other-block", top: 15},
+ });
+ assert.equal(state.storage[constants.LOCAL_FILEPOSITION].document, controls.scroll);
+ (controls.scroll as {top: number}).top = 100;
+ state.mobile.editor = editor("other-box");
+ assert.equal((clone(requests[0].value) as {document: {top: number}}).document.top, 42);
+ succeed(requests[0]);
+ assert.equal(await saving, true);
+});
+
+test("encrypted legacy layout capture removes its global position before persisting", async () => {
+ const {api, state, requests, scrollCalls} = loadLayout();
+ state.mobile.editor = editor("encrypted-box");
+ const positions = state.storage[constants.LOCAL_FILEPOSITION];
+ positions.document = {id: "secret-block", top: 80};
+ positions.other = {id: "public-block", top: 15};
+ const saving = api.saveMobileLayout();
+ assert.equal(scrollCalls.length, 1);
+ assert.equal(scrollCalls[0].force, true);
+ assert.equal(Object.prototype.hasOwnProperty.call(positions, "document"), false);
+ assert.equal(requests.length, 1);
+ assert.deepEqual(clone(requests[0].value), {other: {id: "public-block", top: 15}});
+ succeed(requests[0]);
+ assert.equal(await saving, true);
+});
+
+test("legacy layout saves report consumed storage failures", async () => {
+ const {api, state, requests} = loadLayout();
+ state.mobile.editor = editor();
+ const saving = api.saveMobileLayout();
+ requests[0].resolve();
+ assert.equal(await saving, false);
+});
+
+test("the aggregate deadline bounds a queued layout save without letting later writes overtake it", async () => {
+ const {api, state, requests, advance, timers} = loadLayout(true);
+ const first = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, {revision: 1});
+ const second = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, {revision: 2});
+ state.mobile.tabs = {save: () => api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, {revision: 3})};
+ let settled = false;
+ const layout = api.saveMobileLayout();
+ void layout.then(() => { settled = true; });
+ await advance(9999);
+ assert.equal(settled, false);
+ assert.equal(requests.length, 1);
+ await advance(1);
+ assert.equal(await first, false);
+ assert.equal(await layout, false);
+ assert.equal(requests[0].signal.aborted, true);
+ assert.equal(requests.length, 2);
+ assert.deepEqual(clone(requests[1].value), {revision: 2});
+ const fourth = api.saveMobileStorage(constants.LOCAL_MOBILE_TABS, {revision: 4});
+ await advance(10000);
+ assert.equal(await second, false);
+ assert.equal(requests.length, 3);
+ assert.deepEqual(clone(requests[2].value), {revision: 3});
+ succeed(requests[2]);
+ await flush();
+ assert.equal(requests.length, 4);
+ assert.deepEqual(clone(requests[3].value), {revision: 4});
+ succeed(requests[3]);
+ assert.equal(await fourth, true);
+ assert.equal(timers.size, 0);
+});
+
+test("an unresponsive tab saver is bounded by the layout deadline", async () => {
+ const {api, state, advance, timers} = loadLayout();
+ state.mobile.tabs = {save: () => new Promise<boolean>(() => {})};
+ const saving = api.saveMobileLayout();
+ await advance(10000);
+ assert.equal(await saving, false);
+ assert.equal(timers.size, 0);
+});
diff --git a/app/src/mobile/util/saveLayout.ts b/app/src/mobile/util/saveLayout.ts
new file mode 100644
index 0000000000..84e31b199b
--- /dev/null
+++ b/app/src/mobile/util/saveLayout.ts
@@ -0,0 +1,67 @@
+import {Constants} from "../../constants";
+import {saveScroll} from "../../protyle/scroll/saveScroll";
+import {setStorageVal} from "../../protyle/util/compatibility";
+import {isEncryptedBox} from "../../util/pathName";
+import {withFetchTimeout} from "../../util/fetchTimeout";
+
+const pendingWrites = new Map<string, Promise<boolean>>();
+
+export const saveMobileStorage = (key: string, value: unknown): Promise<boolean> => {
+ if (window.siyuan.config.readonly || window.siyuan.isPublish) {
+ return Promise.resolve(true);
+ }
+ // 排队前复制快照,避免页签切换和历史记录修改影响尚未写入的内容。
+ const snapshot = JSON.parse(JSON.stringify(value));
+ const write = async () => {
+ let saved = false;
+ try {
+ await setStorageVal(key, snapshot, () => { saved = true; }, 10000);
+ } catch (error) {
+ console.warn("Save mobile layout failed", error);
+ return false;
+ }
+ return saved;
+ };
+ if (key !== Constants.LOCAL_MOBILE_TABS) {
+ return write();
+ }
+ const pending = pendingWrites.get(key);
+ const result = pending ? pending.then(write) : write();
+ pendingWrites.set(key, result);
+ void result.then(() => {
+ if (pendingWrites.get(key) === result) {
+ pendingWrites.delete(key);
+ }
+ });
+ return result;
+};
+
+const saveLayout = async (): Promise<boolean> => {
+ if (window.siyuan.mobile.tabs) {
+ return window.siyuan.mobile.tabs.save();
+ }
+ const protyle = window.siyuan.mobile.editor?.protyle;
+ if (!protyle) {
+ return true;
+ }
+ const scroll = saveScroll(protyle, true) as IScrollAttr | undefined;
+ if (!scroll) {
+ return true;
+ }
+ const positions = window.siyuan.storage[Constants.LOCAL_FILEPOSITION];
+ if (isEncryptedBox(protyle.notebookId)) {
+ delete positions[protyle.block.rootID];
+ } else {
+ positions[protyle.block.rootID] = scroll;
+ }
+ return saveMobileStorage(Constants.LOCAL_FILEPOSITION, positions);
+};
+
+export const saveMobileLayout = (): Promise<boolean> => {
+ // 限制整个保存流程的等待时间,退出和锁屏不逐个等待积压的请求超时。
+ const saved = saveLayout();
+ return withFetchTimeout(() => saved, undefined, 10000).catch((error) => {
+ console.warn("Save mobile layout failed", error);
+ return false;
+ });
+};
diff --git a/app/src/plugin/API.ts b/app/src/plugin/API.ts
index 863564958f..ae1a7c9f75 100644
--- a/app/src/plugin/API.ts
+++ b/app/src/plugin/API.ts
@@ -29,7 +29,7 @@ import {getAllEditor} from "../layout/getAll";
import {openPluginSetting} from "../config";
import {openAttr, openFileAttr} from "../menus/commonMenuItem";
import {globalCommand} from "../boot/globalEvent/command/global";
-import {saveScroll} from "../protyle/scroll/saveScroll";
+import {saveMobileLayout} from "../mobile/util/saveLayout";
import {hasClosestByClassName} from "../protyle/util/hasClosest";
import type {MobileFiles} from "../mobile/dock/MobileFiles";
import type {Files} from "../layout/dock/Files";
@@ -224,14 +224,13 @@ const openAttributePanel = (options: {
const saveLayout = (cb: () => void) => {
/// #if MOBILE
- if (window.siyuan.mobile.editor) {
- const result = saveScroll(window.siyuan.mobile.editor.protyle);
- if (cb && result instanceof Promise) {
- result.then(() => {
- cb();
- });
+ void saveMobileLayout().then((saved) => {
+ if (saved) {
+ cb?.();
+ } else {
+ showMessage(window.siyuan.languages.mobileLayoutSaveError, 6000, "error");
}
- }
+ });
/// #else
exportLayout({cb, errorExit: false});
/// #endif