An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support editable block reference popovers on mobile https://github.com/siyuan-note/siyuan/issues/20115
Danielfdb88632afb2
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 0d79fcb8ea..108880eaf9 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,5 @@{+ "viewRefContent": "عرض المحتوى المشار إليه","bazaarStars": "عدد نجوم مستودع GitHub","bazaarFeedbackTip": "إرسال ملاحظات عبر GitHub Issues","performOCR": "إجراء OCR",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex b81ca20ccf..6fbdbb3aaa 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,5 @@{+ "viewRefContent": "Referenzierten Inhalt anzeigen","bazaarStars": "Anzahl der Sterne des GitHub-Repositorys","bazaarFeedbackTip": "Feedback über GitHub Issues geben","performOCR": "OCR ausführen",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex f5dff91e8c..4f226bd242 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,5 @@{+ "viewRefContent": "View referenced content","bazaarStars": "GitHub repository star count","bazaarFeedbackTip": "Send feedback via GitHub Issues","performOCR": "Run OCR",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex d1f6ac0d1d..1530c30f06 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,5 @@{+ "viewRefContent": "Ver contenido referenciado","bazaarStars": "Número de estrellas del repositorio de GitHub","bazaarFeedbackTip": "Enviar comentarios a través de GitHub Issues","performOCR": "Ejecutar OCR",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex e5c0d6d964..2a99753662 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,5 @@{+ "viewRefContent": "Afficher le contenu référencé","bazaarStars": "Nombre d’étoiles du dépôt GitHub","bazaarFeedbackTip": "Envoyer des commentaires via GitHub Issues","performOCR": "Exécuter l’OCR",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 56309f7ab9..1127519e14 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,5 @@{+ "viewRefContent": "הצג את התוכן שאליו מפנים","bazaarStars": "מספר הכוכבים של מאגר GitHub","bazaarFeedbackTip": "שליחת משוב באמצעות GitHub Issues","performOCR": "בצע OCR",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex a1aa225dad..99bd0b792c 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,5 @@{+ "viewRefContent": "संदर्भित सामग्री देखें","bazaarStars": "GitHub रिपॉज़िटरी के सितारों की संख्या","bazaarFeedbackTip": "GitHub Issues के माध्यम से प्रतिक्रिया भेजें","performOCR": "OCR करें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 3d95143a39..e1ff5e4e17 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,5 @@{+ "viewRefContent": "Lihat konten yang dirujuk","bazaarStars": "Jumlah bintang repositori GitHub","bazaarFeedbackTip": "Kirim masukan melalui GitHub Issues","performOCR": "Jalankan OCR",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex e7e0b5b95a..130e0fb2c8 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,5 @@{+ "viewRefContent": "Visualizza il contenuto a cui si fa riferimento","bazaarStars": "Numero di stelle del repository GitHub","bazaarFeedbackTip": "Invia feedback tramite GitHub Issues","performOCR": "Esegui OCR",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 6d6f909230..4e017de68b 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,5 @@{+ "viewRefContent": "参照先の内容を表示","bazaarStars": "GitHub リポジトリのスター数","bazaarFeedbackTip": "GitHub Issues からフィードバックを送信","performOCR": "OCR を実行",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex fb8bad9b78..4861c79144 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,5 @@{+ "viewRefContent": "참조된 콘텐츠 보기","bazaarStars": "GitHub 저장소의 스타 수","bazaarFeedbackTip": "GitHub Issues를 통해 피드백 보내기","performOCR": "OCR 실행",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 319c01796a..7e2037584f 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,5 @@{+ "viewRefContent": "Inhoud waarnaar wordt verwezen bekijken","bazaarStars": "Aantal sterren van de GitHub-repository","bazaarFeedbackTip": "Feedback versturen via GitHub Issues","performOCR": "OCR uitvoeren",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 9d74357acc..c22629e50c 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,5 @@{+ "viewRefContent": "Wyświetl treść, do której prowadzi odnośnik","bazaarStars": "Liczba gwiazdek repozytorium GitHub","bazaarFeedbackTip": "Prześlij opinię przez GitHub Issues","performOCR": "Wykonaj OCR",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 77f79ce451..49ebb68ae0 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,5 @@{+ "viewRefContent": "Ver conteúdo referenciado","bazaarStars": "Número de estrelas do repositório do GitHub","bazaarFeedbackTip": "Enviar comentários pelo GitHub Issues","performOCR": "Executar OCR",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 6f036142ed..75703b4b25 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,5 @@{+ "viewRefContent": "Просмотреть содержимое по ссылке","bazaarStars": "Количество звёзд репозитория GitHub","bazaarFeedbackTip": "Отправить отзыв через GitHub Issues","performOCR": "Выполнить OCR",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex ae4809faeb..c03d94bb30 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,5 @@{+ "viewRefContent": "Zobraziť odkazovaný obsah","bazaarStars": "Počet hviezdičiek repozitára GitHub","bazaarFeedbackTip": "Odoslať spätnú väzbu cez GitHub Issues","performOCR": "Spustiť OCR",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 7d687a1a96..0a2a7e900b 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,5 @@{+ "viewRefContent": "Prikaži sadržaj na koji se upućuje","bazaarStars": "Број звездица GitHub репозиторијума","bazaarFeedbackTip": "Пошаљите повратне информације преко GitHub Issues","performOCR": "Izvrši OCR",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 8951353f4c..f9663b1716 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,5 @@{+ "viewRefContent": "ดูเนื้อหาที่อ้างอิง","bazaarStars": "จำนวนดาวของที่เก็บ GitHub","bazaarFeedbackTip": "ส่งข้อเสนอแนะผ่าน GitHub Issues","performOCR": "ดำเนินการ OCR",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 2a50062b87..021d5abf31 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,5 @@{+ "viewRefContent": "Referans verilen içeriği görüntüle","bazaarStars": "GitHub deposunun yıldız sayısı","bazaarFeedbackTip": "GitHub Issues üzerinden geri bildirim gönderin","performOCR": "OCR çalıştır",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 72b81e2070..25735537e6 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,5 @@{+ "viewRefContent": "Переглянути вміст за посиланням","bazaarStars": "Кількість зірок репозиторію GitHub","bazaarFeedbackTip": "Надіслати відгук через GitHub Issues","performOCR": "Виконати OCR",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 68ed9b3e8c..4bc438a776 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,5 @@{+ "viewRefContent": "查看引用内容","bazaarStars": "GitHub 仓库星标数","bazaarFeedbackTip": "通过 GitHub Issues 反馈","performOCR": "进行 OCR",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex a5116d3d51..e055b426fa 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,5 @@{+ "viewRefContent": "查看引用內容","bazaarStars": "GitHub 儲存庫星標數","bazaarFeedbackTip": "透過 GitHub Issues 回饋","performOCR": "進行 OCR",diff --git a/app/src/assets/scss/main/_mobile.scss b/app/src/assets/scss/main/_mobile.scssindex 829ca3b12c..ec58fbb452 100644--- a/app/src/assets/scss/main/_mobile.scss+++ b/app/src/assets/scss/main/_mobile.scss@@ -1821,6 +1821,26 @@ body.mobile-topbar--merged {}}+.mobile-reference-dialog {+ .mobile-reference-sheet {+ // 按键盘上方的可见视口保留原文区域,不随键盘自动扩展到全屏。+ max-height: 60%;+ }++ .b3-dialog__body {+ box-sizing: border-box;+ }++ .mobile-reference-editor {+ min-height: 0;+ }++ &--compact .b3-dialog__header {+ // 窄小视口中将空间留给正文,标题仍为对话框提供无障碍名称。+ display: none;+ }+}+.mobile-backlinks-dialog {.mobile-backlinks-content {flex: 0 1 auto;diff --git a/app/src/menus/protyle.ts b/app/src/menus/protyle.tsindex 934e2e4b9e..0476f611f7 100644--- a/app/src/menus/protyle.ts+++ b/app/src/menus/protyle.ts@@ -61,6 +61,9 @@ import {checkFold, genTagList, renameTag} from "../util/noRelyPCFunction";import {hideElements} from "../protyle/ui/hideElements";import {emitOpenMenu} from "../plugin/EventBus";import {openMobileFileById} from "../mobile/editor";+/// #if MOBILE+import {openMobileReference} from "../mobile/util/openReference";+/// #endifimport {genAssetHTML, renderAssetsPreview} from "../asset/renderAssets";import {insertHTML} from "../protyle/util/insertHTML";import {upDownHint} from "../util/upDownHint";@@ -682,6 +685,16 @@ export const refMenu = (protyle: IProtyle, element: HTMLElement) => {writeText(protyle.lute.BlockDOM2StdMd(element.outerHTML).trim());}}).element);+ /// #if MOBILE+ window.siyuan.menus.menu.append(new MenuItem({+ id: "viewRefContent",+ label: window.siyuan.languages.viewRefContent,+ icon: "iconPreview",+ click: () => {+ void openMobileReference(protyle, refBlockId);+ }+ }).element);+ /// #endifif (!protyle.disabled) {window.siyuan.menus.menu.append(new MenuItem({id: "cut",diff --git a/app/src/mobile/editor.ts b/app/src/mobile/editor.tsindex 81d558ad77..5de4c33d21 100644--- a/app/src/mobile/editor.ts+++ b/app/src/mobile/editor.ts@@ -23,7 +23,8 @@ import {restoreMobileTopBarLayout} from "./util/mobileTopBar";import {stickyRow} from "../protyle/render/av/row";import {invalidateTrackedRanges} from "../protyle/util/trackedRange";import {getActiveMobileSecondaryEditor} from "./util/secondaryEditors";-import {closeMobileBacklinkSheets} from "./util/backlinkPanels";+import {closeMobileEditorSheets} from "./util/MobileEditorDialog";+import {invalidateMobileReferenceOpen} from "./util/openReference";import {closeAVCellEditor} from "../protyle/render/av/cellEditor";export const getCurrentEditor = () => {@@ -70,6 +71,22 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[isValid: () => boolean = () => true, signal?: AbortSignal,scrollAttr?: IScrollAttr, updateRecent = true,onFailure?: (invalid?: boolean) => void, keepPanels = false) => {+ invalidateMobileReferenceOpen();+ const closing = closeMobileEditorSheets();+ if (closing) {+ void closing.then(() => {+ if (isValid() && !signal?.aborted) {+ loadMobileFileById(app, id, action, scrollPosition, notebookId, afterOpen, forceReload,+ isValid, signal, scrollAttr, updateRecent, onFailure, keepPanels);+ } else {+ onFailure?.();+ }+ }).catch(error => {+ console.error(error);+ onFailure?.();+ });+ return;+ }let completed = false;let titleHidden = false;const complete = (protyle: IProtyle) => {@@ -331,7 +348,7 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[export const openMobileFileById = (app: App, id: string, action: TProtyleAction[] = [Constants.CB_GET_HL],scrollPosition?: ScrollLogicalPosition, notebookId?: string,afterOpen?: (protyle: IProtyle) => void, forceReload = false) => {- const closing = closeMobileBacklinkSheets();+ const closing = closeMobileEditorSheets();if (closing) {void closing.then(() => openMobileFileById(app, id, action, scrollPosition, notebookId, afterOpen, forceReload)).catch(error => console.error(error));@@ -363,7 +380,7 @@ export const openMobileFileByIdInNewTab = (app: App, id: string,action: TProtyleAction[] = [Constants.CB_GET_HL],scrollPosition?: ScrollLogicalPosition, notebookId?: string,afterOpen?: (protyle: IProtyle) => void) => {- const closing = closeMobileBacklinkSheets();+ const closing = closeMobileEditorSheets();if (closing) {void closing.then(() => openMobileFileByIdInNewTab(app, id, action, scrollPosition, notebookId, afterOpen)).catch(error => console.error(error));diff --git a/app/src/mobile/util/MobileEditorDialog.test.ts b/app/src/mobile/util/MobileEditorDialog.test.tsnew file mode 100644index 0000000000..cf2d6e312c--- /dev/null+++ b/app/src/mobile/util/MobileEditorDialog.test.ts@@ -0,0 +1,140 @@+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";++const compiled = transpileModule(readFileSync(join(__dirname, "MobileEditorDialog.ts"), "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},+}).outputText;++const deferred = () => {+ let resolve: () => void;+ let reject: (error: Error) => void;+ const promise = new Promise<void>((done, fail) => { resolve = done; reject = fail; });+ return {promise, resolve, reject};+};++const setup = () => {+ const messages: string[] = [];+ const errors: unknown[] = [];+ class Dialog {+ destroyed = 0;+ destroy() { this.destroyed++; }+ }+ const api = {} as typeof import("./MobileEditorDialog");+ const modules: Record<string, unknown> = {+ "../../dialog": {Dialog},+ "../../dialog/message": {showMessage: (message: string) => messages.push(message)},+ "../../util/escape": {escapeHtml: (value: string) => value.replace(/</g, "<").replace(/>/g, ">")},+ };+ runInNewContext(compiled, {exports: api, require: (name: string) => {+ assert.ok(modules[name], `Unexpected module: ${name}`);+ return modules[name];+ }, console: {error: (error: unknown) => errors.push(error)}});+ const dialog = () => new api.MobileEditorDialog({content: "editor"}) as+ InstanceType<typeof api.MobileEditorDialog> & {destroyed: number};+ return {...api, dialog, messages, errors};+};++test("registered editor sheets coalesce concurrent close requests and wait for every save", async () => {+ const fixture = setup();+ assert.equal(fixture.closeMobileEditorSheets(), undefined);+ const first = fixture.dialog();+ const second = fixture.dialog();+ const firstSave = deferred();+ const secondSave = deferred();+ let firstCalls = 0;+ let secondCalls = 0;+ first.beforeClose = () => { firstCalls++; return firstSave.promise; };+ second.beforeClose = () => { secondCalls++; return secondSave.promise; };+ first.register();+ first.register();+ second.register();+ const closing = first.close();+ assert.equal(first.close(), closing);+ let completed = false;+ const all = fixture.closeMobileEditorSheets().then(() => { completed = true; });+ await Promise.resolve();+ assert.equal(firstCalls, 1);+ assert.equal(secondCalls, 1);+ assert.equal(first.destroyed, 0);+ assert.equal(second.destroyed, 0);+ firstSave.resolve();+ await closing;+ assert.equal(first.destroyed, 1);+ assert.equal(second.destroyed, 0);+ assert.equal(completed, false);+ secondSave.resolve();+ await all;+ assert.equal(second.destroyed, 1);+ assert.equal(fixture.closeMobileEditorSheets(), undefined);+});++test("a failed close keeps the sheet registered and can be retried without destroying its content", async () => {+ const fixture = setup();+ const dialog = fixture.dialog();+ const failure = new Error("<save failed>");+ let attempts = 0;+ dialog.beforeClose = async () => {+ if (++attempts === 1) {+ throw failure;+ }+ };+ dialog.register();+ const closing = dialog.close();+ await assert.rejects(closing, failure);+ assert.equal(dialog.destroyed, 0);+ assert.deepEqual(fixture.messages, ["Error: <save failed>"]);+ await fixture.closeMobileEditorSheets();+ assert.equal(attempts, 2);+ assert.equal(dialog.destroyed, 1);+ assert.notEqual(dialog.close(), closing);+ assert.equal(fixture.closeMobileEditorSheets(), undefined);+});++test("ordinary destroy goes through the save guard and reports a rejected save", async () => {+ const fixture = setup();+ const dialog = fixture.dialog();+ const save = deferred();+ dialog.beforeClose = () => save.promise;+ dialog.register();+ dialog.destroy();+ assert.equal(dialog.destroyed, 0);+ const failure = new Error("offline");+ save.reject(failure);+ await assert.rejects(dialog.close(), failure);+ await Promise.resolve();+ assert.equal(dialog.destroyed, 0);+ assert.deepEqual(fixture.errors, [failure]);+});++test("security discard unregisters immediately without starting another save", async () => {+ const fixture = setup();+ const dialog = fixture.dialog();+ let saves = 0;+ dialog.beforeClose = async () => { saves++; };+ dialog.register();+ dialog.discard();+ assert.equal(saves, 0);+ assert.equal(dialog.destroyed, 1);+ assert.equal(fixture.closeMobileEditorSheets(), undefined);+});++test("security discard does not revive a sheet or report a stale save failure", async () => {+ const fixture = setup();+ const dialog = fixture.dialog();+ const save = deferred();+ dialog.beforeClose = () => save.promise;+ dialog.register();+ const closing = dialog.close();+ await Promise.resolve();+ dialog.discard();+ assert.equal(dialog.destroyed, 1);+ assert.equal(fixture.closeMobileEditorSheets(), undefined);+ save.reject(new Error("notebook is locked"));+ await closing;+ assert.deepEqual(fixture.messages, []);+ assert.equal(fixture.closeMobileEditorSheets(), undefined);+});diff --git a/app/src/mobile/util/MobileEditorDialog.ts b/app/src/mobile/util/MobileEditorDialog.tsnew file mode 100644index 0000000000..7a9ae387b5--- /dev/null+++ b/app/src/mobile/util/MobileEditorDialog.ts@@ -0,0 +1,52 @@+import {Dialog} from "../../dialog";+import {showMessage} from "../../dialog/message";+import {escapeHtml} from "../../util/escape";++const sheets = new Set<MobileEditorDialog>();++export const closeMobileEditorSheets = () => {+ if (sheets.size) {+ return Promise.all(Array.from(sheets, dialog => dialog.close())).then(() => undefined);+ }+};++export class MobileEditorDialog extends Dialog {+ public beforeClose: () => Promise<void>;+ private closing?: Promise<void>;+ private discarded = false;++ public register() {+ sheets.add(this);+ }++ public close() {+ if (this.discarded) {+ return Promise.resolve();+ }+ if (!this.closing) {+ this.closing = Promise.resolve().then(() => this.beforeClose?.()).then(() => {+ sheets.delete(this);+ super.destroy();+ }).catch(error => {+ if (this.discarded) {+ return;+ }+ this.closing = undefined;+ showMessage(escapeHtml(String(error)));+ throw error;+ });+ }+ return this.closing;+ }++ public destroy() {+ void this.close().catch(error => console.error(error));+ }++ // 笔记本锁定或内容删除时立即注销面板,不等待已经失去访问权限的保存请求。+ public discard() {+ this.discarded = true;+ sheets.delete(this);+ super.destroy();+ }+}diff --git a/app/src/mobile/util/backlinkPanels.ts b/app/src/mobile/util/backlinkPanels.tsindex ece64f0fc4..639afaa53c 100644--- a/app/src/mobile/util/backlinkPanels.ts+++ b/app/src/mobile/util/backlinkPanels.ts@@ -1,27 +1,15 @@import type {BacklinkContent} from "../../layout/dock/BacklinkContent";const panels = new Set<BacklinkContent>();-const sheets = new Map<BacklinkContent, () => Promise<void>>();--export const registerMobileBacklinkPanel = (panel: BacklinkContent, close?: () => Promise<void>) => {+export const registerMobileBacklinkPanel = (panel: BacklinkContent) => {panels.add(panel);- if (close) {- sheets.set(panel, close);- }return () => {- sheets.delete(panel);panels.delete(panel);};};export const getMobileBacklinkPanels = () => Array.from(panels);-export const closeMobileBacklinkSheets = () => {- if (sheets.size) {- return Promise.all(Array.from(sheets.values(), close => close())).then(() => undefined);- }-};-export const removeMobileBacklinkContent = (options: {notebookId?: string, rootIDs?: string[]}) => {panels.forEach(panel => {if ((options.notebookId && panel.notebookId === options.notebookId) ||diff --git a/app/src/mobile/util/bindBottomSheetDialog.ts b/app/src/mobile/util/bindBottomSheetDialog.tsindex 40bfc464bc..fe5bac597c 100644--- a/app/src/mobile/util/bindBottomSheetDialog.ts+++ b/app/src/mobile/util/bindBottomSheetDialog.ts@@ -2,7 +2,7 @@ import type {Dialog} from "../../dialog";import {bindBottomSheetDrag} from "./bindBottomSheetDrag";import {waitForSheetViewport} from "../../menus/sheetOpen";-export const bindBottomSheetDialog = (dialog: Dialog, close: () => Promise<void>) => {+export const bindBottomSheetDialog = (dialog: Dialog, close: () => Promise<void>, afterResize?: () => void) => {dialog.element.classList.add("mobile-bottom-sheet-dialog");const sheet = dialog.element.querySelector<HTMLElement>(".b3-dialog__container");// 初始定位不参与过渡,等待视口恢复后再从底部展开。@@ -27,6 +27,7 @@ export const bindBottomSheetDialog = (dialog: Dialog, close: () => Promise<void>container.style.top = `${viewport.offsetTop}px`;container.style.height = `${viewport.height}px`;}+ afterResize?.();};window.visualViewport?.addEventListener("resize", resize);window.visualViewport?.addEventListener("scroll", resize);diff --git a/app/src/mobile/util/onMessage.ts b/app/src/mobile/util/onMessage.tsindex 1c692cced5..34fcf1dc2c 100644--- a/app/src/mobile/util/onMessage.ts+++ b/app/src/mobile/util/onMessage.ts@@ -32,6 +32,7 @@ import {handleMobileKernelExit} from "./kernelExit";import {sanitizeKernelHTML} from "../../util/hostCapabilities";import {applyEntryVisibility} from "../../config/entryVisibility/runtime";import {removeMobileBacklinkContent} from "./backlinkPanels";+import {removeMobileReferenceSheet} from "./openReference";import {isPaidUser, needSubscribe} from "../../util/needSubscribe";let statusTimeout: number;@@ -131,6 +132,7 @@ export const onMessage = (app: App, data: IWebSocketData) => {case "removeBox": {closeNotebookHistoryDialogs(data.data.box);removeMobileBacklinkContent({notebookId: data.data.box});+ removeMobileReferenceSheet({notebookId: data.data.box});window.siyuan.mobile.tabs?.removeNotebook(data.data.box);break;}@@ -139,6 +141,7 @@ export const onMessage = (app: App, data: IWebSocketData) => {break;case "removeDoc":removeMobileBacklinkContent({rootIDs: data.data.ids});+ removeMobileReferenceSheet({rootIDs: data.data.ids});window.siyuan.mobile.tabs?.removeRoots(data.data.ids);if (window.siyuan.config.onboarding?.newUser && !window.siyuan.config.onboarding.dismissed &&data.data.ids.includes(window.siyuan.config.onboarding.documentID)) {diff --git a/app/src/mobile/util/openBacklinks.ts b/app/src/mobile/util/openBacklinks.tsindex 0469e7e512..3f625970c6 100644--- a/app/src/mobile/util/openBacklinks.ts+++ b/app/src/mobile/util/openBacklinks.ts@@ -1,35 +1,11 @@-import {Dialog} from "../../dialog";+import {MobileEditorDialog} from "./MobileEditorDialog";import {BacklinkContent} from "../../layout/dock/BacklinkContent";import {activeBlur} from "./keyboardToolbar";import {registerMobileBacklinkPanel} from "./backlinkPanels";import {clearActiveMobileSecondaryEditor, flushMobileSecondaryEditor} from "./secondaryEditors";-import {showMessage} from "../../dialog/message";-import {escapeHtml} from "../../util/escape";import {bindBottomSheetDialog} from "./bindBottomSheetDialog";-class MobileBacklinkDialog extends Dialog {- public beforeClose: () => Promise<void>;- private closing?: Promise<void>;-- public close() {- if (!this.closing) {- this.closing = Promise.resolve().then(() => this.beforeClose?.()).then(() => {- super.destroy();- }).catch(error => {- this.closing = undefined;- showMessage(escapeHtml(String(error)));- throw error;- });- }- return this.closing;- }-- public destroy() {- void this.close().catch(error => console.error(error));- }-}--let currentDialog: MobileBacklinkDialog;+let currentDialog: MobileEditorDialog;let openVersion = 0;export const openMobileBacklinks = async (protyle: IProtyle, blockId: string) => {@@ -45,7 +21,7 @@ export const openMobileBacklinks = async (protyle: IProtyle, blockId: string) =>if (version !== openVersion || !protyle.element.isConnected) {return;}- const dialog = new MobileBacklinkDialog({+ const dialog = new MobileEditorDialog({content: '<div class="mobile-backlinks-content fn__flex-column"></div>',width: "100vw",height: "auto",@@ -91,6 +67,7 @@ export const openMobileBacklinks = async (protyle: IProtyle, blockId: string) =>clearActiveMobileSecondaryEditor();}};- const unregisterPanel = registerMobileBacklinkPanel(panel, () => dialog.close());+ dialog.register();+ const unregisterPanel = registerMobileBacklinkPanel(panel);const disposeSheet = bindBottomSheetDialog(dialog, () => dialog.close());};diff --git a/app/src/mobile/util/openReference.test.ts b/app/src/mobile/util/openReference.test.tsnew file mode 100644index 0000000000..3968b04cdc--- /dev/null+++ b/app/src/mobile/util/openReference.test.ts@@ -0,0 +1,674 @@+import * as assert from "node:assert/strict";+import {spawnSync} from "node:child_process";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import {join} from "node:path";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {compile} from "sass";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const transpile = (file: string) => transpileModule(readFileSync(join(__dirname, file), "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},+}).outputText;+const referenceSource = transpile("openReference.ts");+const dialogSource = transpile("MobileEditorDialog.ts");+const sheetSource = transpile("bindBottomSheetDialog.ts");+const saveSource = transpile("../../protyle/util/editorSave.ts");+const editorSessionSource = transpile("../../protyle/render/av/editorSession.ts");+const cellEditorSource = transpile("../../protyle/render/av/cellEditor.ts");++const deferred = <T>() => {+ let resolve: (value: T) => void;+ let reject: (error: Error) => void;+ const promise = new Promise<T>((done, fail) => { resolve = done; reject = fail; });+ return {promise, resolve, reject};+};++class EventTargetMock {+ listeners = new Map<string, Set<() => void>>();+ addEventListener(type: string, callback: () => void) {+ if (!this.listeners.has(type)) {+ this.listeners.set(type, new Set());+ }+ this.listeners.get(type).add(callback);+ }+ removeEventListener(type: string, callback: () => void) { this.listeners.get(type)?.delete(callback); }+ dispatch(type: string) { this.listeners.get(type)?.forEach(callback => callback()); }+ listenerCount() { return Array.from(this.listeners.values()).reduce((sum, callbacks) => sum + callbacks.size, 0); }+}++class ElementMock extends EventTargetMock {+ isConnected = true;+ parentElement?: ElementMock;+ dataset: Record<string, string> = {};+ blurred = false;+ style: Record<string, string> = {};+ attributes = new Map<string, string>();+ classes = new Set<string>();+ classList = {+ add: (name: string) => this.classes.add(name),+ remove: (name: string) => this.classes.delete(name),+ contains: (name: string) => this.classes.has(name),+ toggle: (name: string, enabled: boolean) => enabled ? this.classes.add(name) : this.classes.delete(name),+ };+ children = new Map<string, ElementMock>();+ cleared = false;+ setAttribute(name: string, value: string) { this.attributes.set(name, value); }+ hasAttribute(name: string) { return this.attributes.has(name); }+ removeAttribute(name: string) { this.attributes.delete(name); }+ querySelector(selector: string) { return this.children.get(selector); }+ querySelectorAll(selector: string): ElementMock[] {+ return selector === "[data-node-id]" ? Array.from(this.children.values()).flatMap(child =>+ [...child.dataset.nodeId ? [child] : [], ...child.querySelectorAll(selector)]) : [];+ }+ prepend(element: ElementMock) { this.children.set("handle", element); }+ remove() { this.isConnected = false; }+ contains(element: ElementMock): boolean {+ return this === element || Array.from(this.children.values()).some(child => child.contains(element));+ }+ dispatchEvent(event: {type: string, bubbles?: boolean}) {+ this.dispatch(event.type);+ if (event.bubbles) {+ this.parentElement?.dispatchEvent(event);+ }+ return true;+ }+ blur() { this.blurred = true; }+ replaceChildren() { this.cleared = true; this.children.clear(); }+}++const setup = (readonly = false) => {+ const requests: Array<ReturnType<typeof deferred<any>> & {id: string}> = [];+ const messages: string[] = [];+ const dialogs: DialogMock[] = [];+ const editors: ProtyleMock[] = [];+ const registered = new Map<ProtyleMock, () => void>();+ const destroyCallbacks: Array<() => void> = [];+ const flushes: ProtyleMock[] = [];+ const refreshed: any[] = [];+ const titleEvents: string[] = [];+ const cellMasks: ElementMock[] = [];+ let flush: (editor: ProtyleMock) => Promise<void> = () => Promise.resolve();+ let disposedBindings = 0;+ const viewport = {top: 0, bottom: 800};+ const document = {activeElement: new ElementMock(), createElement: () => new ElementMock(),+ querySelectorAll: (selector: string) => {+ assert.ok([".av__mask", ".av__mask:not(.av__richtext-mask)"].includes(selector));+ return cellMasks.filter(mask => mask.isConnected &&+ (selector === ".av__mask" || !mask.classList.contains("av__richtext-mask")));+ }};+ const window = Object.assign(new EventTargetMock(), {+ innerHeight: 800,+ visualViewport: Object.assign(new EventTargetMock(), {offsetTop: 0, height: 800}),+ siyuan: {config: {readonly}, languages: {viewRefContent: "Reference", refExpired: "Expired", uploading: "Uploading",+ settingsPendingSaveError: "Pending save failed"},+ menus: {menu: {remove() {}}}, mobile: {size: {isLandscape: false, portrait: {height1: 800}}}},+ });+ class DialogMock {+ element = new ElementMock();+ destroyed = 0;+ constructor(public options: any) {+ for (const selector of [".b3-dialog", ".b3-dialog__body", ".b3-dialog__container", ".b3-dialog__scrim",+ ".mobile-reference-editor"]) {+ this.element.children.set(selector, new ElementMock());+ }+ this.element.querySelector(".b3-dialog__container").children.set(".b3-dialog__header", new ElementMock());+ this.element.classList.add("b3-dialog--open");+ dialogs.push(this);+ }+ destroy() {+ if (!this.destroyed) {+ this.destroyed++;+ destroyCallbacks.push(() => { this.element.isConnected = false; this.options.destroyCallback?.(); });+ }+ }+ }+ class ProtyleMock {+ protyle: any;+ destroyed = 0;+ uploading = false;+ constructor(public app: unknown, element: ElementMock, public options: any) {+ this.protyle = {app, element, contentElement: {scrollTop: 0, scrollLeft: 0},+ block: {id: options.blockId, rootID: options.rootId}, notebookId: options.notebookId,+ disabled: readonly, options, id: `editor-${editors.length}`, path: `/${options.rootId}.sy`,+ title: options.render.title ? {flushPendingInput: () => titleEvents.push("flush"),+ cancelPendingInput: () => titleEvents.push("cancel")} : undefined};+ editors.push(this);+ }+ enable() { assert.fail("The drawer must not override the editor's readonly policy"); }+ isUploading() { return this.uploading; }+ destroy() { this.destroyed++; registered.delete(this); }+ }+ const dialogAPI = {} as typeof import("./MobileEditorDialog");+ const sheetAPI = {} as typeof import("./bindBottomSheetDialog");+ const saveAPI = {} as typeof import("../../protyle/util/editorSave");+ const editorSessionAPI = {} as typeof import("../../protyle/render/av/editorSession");+ const cellEditorAPI = {} as typeof import("../../protyle/render/av/cellEditor");+ const api = {} as typeof import("./openReference");+ const modules: Record<string, unknown> = {+ "../../dialog": {Dialog: DialogMock},+ "../../dialog/message": {showMessage: (value: string) => messages.push(value)},+ "../../util/escape": {escapeHtml: (value: string) => value.replace(/</g, "<").replace(/>/g, ">")},+ "../../constants": {Constants: {CB_GET_ALL: "all", CB_GET_CONTEXT: "context"}},+ "../../protyle": {Protyle: ProtyleMock},+ "../../protyle/util/editorSave": saveAPI,+ "../../protyle/render/av/editorSession": editorSessionAPI,+ "../../protyle/render/av/cellEditor": cellEditorAPI,+ "../../util/fetch": {fetchSyncPost: (url: string, data: {id: string}) => {+ assert.equal(url, "/api/block/getBlockInfo");+ const request = {...deferred<any>(), id: data.id};+ requests.push(request);+ return request.promise;+ }},+ "./MobileEditorDialog": dialogAPI,+ "./bindBottomSheetDialog": sheetAPI,+ "./bindBottomSheetDrag": {bindBottomSheetDrag: () => () => { disposedBindings++; }},+ "../../menus/sheetOpen": {waitForSheetViewport: (options: {open: () => void}) => {+ options.open();+ return () => {};+ }},+ "./keyboardToolbar": {activeBlur: () => { document.activeElement = new ElementMock(); }},+ "./secondaryEditors": {+ registerMobileSecondaryEditor: (editor: ProtyleMock, remove: () => void) => registered.set(editor, remove),+ flushMobileSecondaryEditor: (editor: ProtyleMock) => { flushes.push(editor); return flush(editor); },+ },+ "./visibleViewport": {getVisibleViewportBounds: () => viewport},+ "../../protyle/scroll/saveScroll": {saveScroll: () => ({scrollTop: 30}),+ getDocByScroll: (options: unknown) => refreshed.push(options)},+ };+ const globals = {window, document, console, CustomEvent, MutationObserver: class {+ observe() {}+ disconnect() {}+ }, require: (name: string) => {+ assert.ok(modules[name], `Unexpected module: ${name}`);+ return modules[name];+ }};+ runInNewContext(dialogSource, {...globals, exports: dialogAPI});+ runInNewContext(sheetSource, {...globals, exports: sheetAPI});+ runInNewContext(saveSource, {...globals, exports: saveAPI});+ runInNewContext(editorSessionSource, {...globals, exports: editorSessionAPI});+ runInNewContext(cellEditorSource, {...globals, exports: cellEditorAPI});+ runInNewContext(referenceSource, {...globals, exports: api});+ const source = {app: {}, element: new ElementMock(), block: {id: "origin-block", rootID: "origin-root"},+ notebookId: "origin-box", contentElement: {scrollTop: 247, scrollLeft: 13}} as unknown as IProtyle;+ const answer = (index: number, rootID = "target-root", box = "target-box") =>+ requests[index].resolve({code: 0, data: {rootID, box}});+ const open = async (blockId = "target-block", protyle = source, rootID = "target-root") => {+ const opening = api.openMobileReference(protyle, blockId);+ answer(requests.length - 1, rootID);+ await opening;+ };+ return {...api, ...dialogAPI, ...saveAPI, ...editorSessionAPI, ...cellEditorAPI,+ source, requests, messages, editors, registered, flushes, refreshed, titleEvents, cellMasks, viewport,+ window, document, answer, open,+ dialogs: dialogs as Array<DialogMock & InstanceType<typeof dialogAPI.MobileEditorDialog>>,+ setFlush: (callback: typeof flush) => { flush = callback; },+ finishDestroy: () => { destroyCallbacks.splice(0).forEach(callback => callback()); },+ disposedBindings: () => disposedBindings};+};++test("only the latest resolved reference opens, without changing the original document or scroll", async () => {+ const fixture = setup();+ const first = fixture.openMobileReference(fixture.source, "first");+ const second = fixture.openMobileReference(fixture.source, "second");+ fixture.answer(1, "second-root");+ await second;+ fixture.answer(0, "first-root");+ await first;+ assert.equal(fixture.editors.length, 1);+ assert.equal(fixture.editors[0].options.blockId, "second");+ assert.equal(fixture.source.block.id, "origin-block");+ assert.equal(fixture.source.contentElement.scrollTop, 247);+ assert.equal(fixture.source.contentElement.scrollLeft, 13);+});++test("late reference responses cannot reopen after the source changes or a notebook locks", async () => {+ for (const invalidation of ["detach", "root", "block", "notebook", "lock"]) {+ const fixture = setup();+ const opening = fixture.openMobileReference(fixture.source, "target");+ if (invalidation === "detach") {+ (fixture.source.element as unknown as ElementMock).isConnected = false;+ } else if (invalidation === "root") {+ fixture.source.block.rootID = "changed-root";+ } else if (invalidation === "block") {+ fixture.source.block.id = "changed-block";+ } else if (invalidation === "notebook") {+ fixture.source.notebookId = "changed-notebook";+ } else {+ fixture.removeMobileReferenceSheet({notebookId: "origin-box"});+ }+ fixture.answer(0);+ await opening;+ assert.equal(fixture.editors.length, 0, invalidation);+ assert.equal(fixture.dialogs.length, 0, invalidation);+ }+});++test("reference editors load whole blocks or ordinary documents and preserve readonly policy", async () => {+ for (const readonly of [false, true]) {+ for (const blockId of ["target-block", "target-root"]) {+ const fixture = setup(readonly);+ await fixture.open(blockId);+ const editor = fixture.editors[0];+ assert.deepEqual(Array.from(editor.options.action), [blockId === "target-root" ? "context" : "all"]);+ assert.equal(editor.options.render.title, blockId === "target-root");+ assert.equal(editor.options.render.scroll, true);+ assert.equal(editor.options.render.gutter, true);+ assert.equal(editor.options.databaseAttr, true);+ assert.equal(editor.options.render.breadcrumb, false);+ assert.equal(editor.options.render.background, false);+ assert.equal(editor.options.typewriterMode, false);+ assert.equal(editor.options.rootId, "target-root");+ assert.equal(editor.options.notebookId, "target-box");+ assert.equal(Object.prototype.hasOwnProperty.call(editor.options, "readonly"), false);+ assert.equal(Object.prototype.hasOwnProperty.call(editor.options, "disabled"), false);+ assert.equal(editor.protyle.disabled, readonly);+ }+ }+});++test("nested reference replacement waits for save and preserves the original reading position", async () => {+ const fixture = setup();+ await fixture.open();+ const oldEditor = fixture.editors[0];+ const oldDialog = fixture.dialogs[0];+ const save = deferred<void>();+ fixture.setFlush(() => save.promise);+ const opening = fixture.openMobileReference(oldEditor.protyle, "nested-block");+ fixture.answer(1, "nested-root");+ await new Promise(resolve => setImmediate(resolve));+ assert.deepEqual(fixture.flushes, [oldEditor]);+ assert.equal(fixture.editors.length, 1);+ assert.equal(oldEditor.destroyed, 0);+ assert.equal(oldDialog.element.hasAttribute("inert"), true);+ save.resolve();+ await opening;+ assert.equal(oldEditor.destroyed, 1);+ assert.equal(fixture.editors.length, 2);+ assert.equal(fixture.registered.size, 1);+ fixture.finishDestroy();+ fixture.source.contentElement.scrollTop = 999;+ fixture.source.contentElement.scrollLeft = 50;+ fixture.setFlush(() => Promise.resolve());+ await fixture.dialogs[1].close();+ fixture.finishDestroy();+ assert.equal(fixture.source.contentElement.scrollTop, 247);+ assert.equal(fixture.source.contentElement.scrollLeft, 13);+ assert.equal(fixture.editors[1].destroyed, 1);+ assert.equal(fixture.registered.size, 0);+});++test("closing a drawer invalidates a nested reference lookup that has not resolved yet", async () => {+ const fixture = setup();+ await fixture.open();+ const editor = fixture.editors[0];+ const opening = fixture.openMobileReference(editor.protyle, "nested-block");+ await fixture.dialogs[0].close();+ assert.equal(editor.destroyed, 1);+ assert.equal(fixture.source.element.isConnected, true);+ assert.equal(fixture.source.block.rootID, "origin-root");+ fixture.answer(1, "nested-root");+ await opening;+ fixture.finishDestroy();+ assert.equal(fixture.editors.length, 1);+ assert.equal(fixture.dialogs.length, 1);+ assert.equal(fixture.registered.size, 0);+ assert.equal(fixture.closeMobileEditorSheets(), undefined);+ assert.equal(fixture.source.contentElement.scrollTop, 247);+ assert.deepEqual(fixture.messages, []);+});++test("a failed save retains the reference content, removes inert, and allows close retry", async () => {+ const fixture = setup();+ await fixture.open();+ const editor = fixture.editors[0];+ const dialog = fixture.dialogs[0];+ fixture.setFlush(() => Promise.reject(new Error("<offline>")));+ await assert.rejects(dialog.close(), /offline/);+ assert.equal(dialog.destroyed, 0);+ assert.equal(editor.destroyed, 0);+ assert.equal(dialog.element.hasAttribute("inert"), false);+ assert.equal(dialog.element.querySelector(".b3-dialog__body").cleared, false);+ assert.equal(fixture.registered.has(editor), true);+ assert.deepEqual(fixture.messages, ["Error: <offline>"]);+ fixture.setFlush(() => Promise.resolve());+ await fixture.closeMobileEditorSheets();+ fixture.finishDestroy();+ assert.equal(editor.destroyed, 1);+ assert.equal(fixture.registered.size, 0);+});++test("raw transaction and title-save failures keep the drawer open until a successful retry", async () => {+ for (const operation of ["transaction", "title"]) {+ const fixture = setup();+ await fixture.open("target-root");+ const editor = fixture.editors[0];+ const dialog = fixture.dialogs[0];+ const transaction = {doOperations: [{action: "update", id: "target-block", data: "edited content"}]};+ const url = operation === "transaction" ? "/api/transactions" : "/api/filetree/renameDoc";+ const payload = operation === "transaction" ? {session: editor.protyle.id, transactions: [transaction]} :+ {notebook: editor.protyle.notebookId, path: editor.protyle.path, title: "Edited title"};+ // Transactions with code 0 but no acknowledged operations must not discard editor content either.+ await fixture.trackEditorSaveRequest(url, payload, Promise.resolve({code: operation === "transaction" ? 0 : 1}));+ await assert.rejects(dialog.close(), /Pending save failed/);+ assert.equal(editor.destroyed, 0);+ assert.equal(dialog.element.hasAttribute("inert"), false);+ assert.equal(fixture.registered.has(editor), true);+ assert.deepEqual(fixture.titleEvents, ["flush"]);+ await fixture.trackEditorSaveRequest(url, payload, Promise.resolve({code: 0, data: [transaction]}));+ await dialog.close();+ assert.equal(editor.destroyed, 1);+ assert.deepEqual(fixture.titleEvents, ["flush", "flush", "cancel"]);+ }+});++test("closing waits for the actual transaction acknowledgement after pending input has flushed", async () => {+ const fixture = setup();+ await fixture.open();+ const editor = fixture.editors[0];+ const transaction = {doOperations: [{action: "update", id: "target-block", data: "edited content"}]};+ const response = deferred<{code: number, data: typeof transaction[]}>();+ fixture.trackEditorSaveRequest("/api/transactions", {session: editor.protyle.id, transactions: [transaction]}, response.promise);+ const closing = fixture.dialogs[0].close();+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(fixture.flushes.length, 1);+ assert.equal(editor.destroyed, 0);+ assert.equal(fixture.dialogs[0].element.hasAttribute("inert"), true);+ response.resolve({code: 0, data: [transaction]});+ await closing;+ assert.equal(editor.destroyed, 1);+});++test("locking a document cancels pending title input instead of transmitting its rename", async () => {+ const fixture = setup();+ await fixture.open("target-root");+ fixture.removeMobileReferenceSheet({notebookId: "target-box"});+ assert.deepEqual(fixture.titleEvents, ["cancel"]);+ assert.equal(fixture.flushes.length, 0);+ assert.equal(fixture.editors[0].destroyed, 1);+});++test("close keeps nested richtext controls usable until every child editor has finished", async () => {+ const fixture = setup();+ await fixture.open("target-root");+ const editor = fixture.editors[0];+ const dialog = fixture.dialogs[0];+ const owner = new ElementMock();+ owner.parentElement = editor.protyle.element;+ editor.protyle.element.children.set("database-block", owner);+ const firstDone = fixture.beginAVEditorSession(owner as unknown as HTMLElement);+ const secondDone = fixture.beginAVEditorSession(owner as unknown as HTMLElement);+ const closing = dialog.close();+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(dialog.element.hasAttribute("inert"), false);+ assert.equal(editor.protyle.element.listenerCount(), 1);+ assert.equal(editor.destroyed, 0);+ assert.equal(fixture.flushes.length, 0);+ assert.deepEqual(fixture.titleEvents, []);+ firstDone();+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(dialog.element.hasAttribute("inert"), false);+ assert.equal(editor.protyle.element.listenerCount(), 1);+ assert.equal(fixture.flushes.length, 0);+ secondDone();+ await closing;+ assert.equal(editor.protyle.element.listenerCount(), 0);+ assert.equal(editor.destroyed, 1);+ assert.deepEqual(fixture.flushes, [editor]);+ assert.deepEqual(fixture.titleEvents, ["flush", "cancel"]);+});++test("locking while a child editor is open releases the close waiter and removes its listeners", async () => {+ const fixture = setup();+ await fixture.open("target-root");+ const editor = fixture.editors[0];+ const dialog = fixture.dialogs[0];+ const childDone = fixture.beginAVEditorSession(editor.protyle.element);+ const closing = dialog.close();+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(editor.protyle.element.listenerCount(), 1);+ fixture.removeMobileReferenceSheet({notebookId: "target-box"});+ await closing;+ fixture.finishDestroy();+ assert.equal(editor.protyle.element.listenerCount(), 0);+ assert.equal(fixture.window.listenerCount(), 0);+ assert.equal(fixture.window.visualViewport.listenerCount(), 0);+ assert.equal(editor.destroyed, 1);+ assert.equal(dialog.destroyed, 1);+ assert.equal(dialog.element.querySelector(".b3-dialog__body").cleared, true);+ assert.deepEqual(fixture.titleEvents, ["cancel"]);+ assert.equal(fixture.flushes.length, 0);+ childDone();+ await Promise.resolve();+ assert.equal(fixture.flushes.length, 0);+ assert.equal(fixture.closeMobileEditorSheets(), undefined);+});++test("close commits only this drawer's plain database cell and ends composition before saving", async () => {+ const fixture = setup();+ await fixture.open();+ const editor = fixture.editors[0];+ const block = new ElementMock();+ block.dataset.nodeId = "drawer-database";+ editor.protyle.element.children.set("database", block);+ const ownCell = new ElementMock();+ ownCell.dataset.avBlockId = "drawer-database";+ const otherCell = new ElementMock();+ otherCell.dataset.avBlockId = "other-database";+ const richtext = new ElementMock();+ richtext.dataset.avBlockId = "drawer-database";+ richtext.classList.add("av__richtext-mask");+ const input = new ElementMock();+ ownCell.children.set("input", input);+ fixture.document.activeElement = input;+ fixture.cellMasks.push(ownCell, otherCell, richtext);+ const closed: string[] = [];+ ownCell.addEventListener(fixture.AV_CELL_EDITOR_CLOSE_EVENT, () => {+ assert.equal(input.blurred, true);+ closed.push("own");+ });+ otherCell.addEventListener(fixture.AV_CELL_EDITOR_CLOSE_EVENT, () => closed.push("other"));+ richtext.addEventListener(fixture.AV_CELL_EDITOR_CLOSE_EVENT, () => closed.push("richtext"));+ fixture.setFlush(() => {+ assert.deepEqual(closed, ["own"]);+ return Promise.resolve();+ });+ await fixture.dialogs[0].close();+ assert.deepEqual(closed, ["own"]);+ assert.equal(editor.destroyed, 1);+});++test("locking removes this drawer's plain and richtext cell masks without submitting either draft", async () => {+ const fixture = setup();+ await fixture.open();+ const block = new ElementMock();+ block.dataset.nodeId = "drawer-database";+ fixture.editors[0].protyle.element.children.set("database", block);+ const ownCell = new ElementMock();+ ownCell.dataset.avBlockId = "drawer-database";+ const richtext = new ElementMock();+ richtext.dataset.avBlockId = "drawer-database";+ richtext.classList.add("av__richtext-mask");+ const otherCell = new ElementMock();+ otherCell.dataset.avBlockId = "other-database";+ const input = new ElementMock();+ ownCell.children.set("input", input);+ fixture.document.activeElement = input;+ fixture.cellMasks.push(ownCell, richtext, otherCell);+ for (const mask of fixture.cellMasks) {+ mask.addEventListener(fixture.AV_CELL_EDITOR_CLOSE_EVENT, () => assert.fail("Lock must not submit cell drafts"));+ }+ fixture.removeMobileReferenceSheet({notebookId: "target-box"});+ assert.equal(ownCell.isConnected, false);+ assert.equal(richtext.isConnected, false);+ assert.equal(otherCell.isConnected, true);+ assert.equal(input.blurred, false);+ assert.equal(fixture.flushes.length, 0);+});++test("locking either notebook or removing either document clears content without waiting for a save", async () => {+ for (const options of [{notebookId: "origin-box"}, {notebookId: "target-box"},+ {rootIDs: ["origin-root"]}, {rootIDs: ["target-root"]}]) {+ const fixture = setup();+ await fixture.open();+ const dialog = fixture.dialogs[0];+ const editor = fixture.editors[0];+ fixture.setFlush(() => { assert.fail("Lock/removal must bypass saving inaccessible content"); });+ fixture.removeMobileReferenceSheet(options);+ assert.equal(dialog.element.querySelector(".b3-dialog__body").cleared, true);+ assert.equal(editor.destroyed, 1);+ assert.equal(dialog.destroyed, 1);+ assert.equal(fixture.registered.size, 0);+ assert.equal(fixture.closeMobileEditorSheets(), undefined);+ fixture.finishDestroy();+ assert.equal(editor.destroyed, 1);+ }+});++test("an active upload prevents closing or replacing the drawer until the upload finishes", async () => {+ const fixture = setup();+ await fixture.open();+ fixture.editors[0].uploading = true;+ await assert.rejects(fixture.dialogs[0].close(), /Uploading/);+ assert.equal(fixture.flushes.length, 0);+ assert.equal(fixture.editors[0].destroyed, 0);+ assert.equal(fixture.dialogs[0].element.hasAttribute("inert"), false);+ await fixture.open("nested", fixture.editors[0].protyle, "nested-root");+ assert.equal(fixture.editors.length, 1);+ fixture.editors[0].uploading = false;+ await fixture.dialogs[0].close();+ assert.equal(fixture.editors[0].destroyed, 1);+});++test("unrelated removals leave the current reference editor available", async () => {+ const fixture = setup();+ await fixture.open();+ fixture.removeMobileReferenceSheet({notebookId: "other-box", rootIDs: ["other-root"]});+ assert.equal(fixture.editors[0].destroyed, 0);+ assert.equal(fixture.dialogs[0].element.querySelector(".b3-dialog__body").cleared, false);+ assert.equal(fixture.registered.size, 1);+});++test("removal during initial editor loading uses the resolved target root", async () => {+ for (const removeFromRegistry of [false, true]) {+ const fixture = setup();+ await fixture.open();+ const editor = fixture.editors[0];+ editor.protyle.block.rootID = "";+ if (removeFromRegistry) {+ fixture.registered.get(editor)();+ } else {+ fixture.removeMobileReferenceSheet({rootIDs: ["target-root"]});+ }+ assert.equal(editor.destroyed, 1);+ assert.equal(fixture.dialogs[0].element.querySelector(".b3-dialog__body").cleared, true);+ assert.equal(fixture.closeMobileEditorSheets(), undefined);+ }+});++test("navigation invalidates an in-flight reference even when the source element is still attached", async () => {+ const fixture = setup();+ const opening = fixture.openMobileReference(fixture.source, "target");+ fixture.invalidateMobileReferenceOpen();+ fixture.answer(0);+ await opening;+ assert.equal(fixture.editors.length, 0);+});++test("viewport changes preserve the original scroll and all resize listeners are removed on close", async () => {+ const fixture = setup();+ await fixture.open();+ const dialog = fixture.dialogs[0];+ const container = dialog.element.querySelector(".b3-dialog");+ assert.equal(dialog.options.height, "60%");+ assert.equal(container.style.height, "800px");+ assert.equal(fixture.window.listenerCount(), 1);+ assert.equal(fixture.window.visualViewport.listenerCount(), 2);+ fixture.viewport.top = 90;+ fixture.viewport.bottom = 440;+ fixture.source.contentElement.scrollTop = 500;+ fixture.window.visualViewport.dispatch("resize");+ assert.equal(container.style.top, "90px");+ assert.equal(container.style.height, "350px");+ assert.equal(dialog.element.classList.contains("mobile-reference-dialog--compact"), true);+ assert.equal(fixture.source.contentElement.scrollTop, 247);+ await dialog.close();+ fixture.finishDestroy();+ assert.equal(fixture.window.listenerCount(), 0);+ assert.equal(fixture.window.visualViewport.listenerCount(), 0);+ assert.equal(fixture.disposedBindings(), 1);+ fixture.viewport.bottom = 700;+ fixture.window.dispatch("resize");+ assert.equal(container.style.height, "350px");+});++test("refresh waits for pending input and ignores content invalidated while saving", async () => {+ const fixture = setup();+ await fixture.open();+ const save = deferred<void>();+ fixture.setFlush(() => save.promise);+ fixture.refreshMobileReferenceSheet(["target-root"], true);+ assert.equal(fixture.refreshed.length, 0);+ fixture.removeMobileReferenceSheet({rootIDs: ["target-root"]});+ save.resolve();+ await Promise.resolve();+ await Promise.resolve();+ assert.equal(fixture.refreshed.length, 0);+});++const mobileCSS = () => compile(join(__dirname, "../../assets/scss/main/_mobile.scss"), {+ logger: {warn() {}, debug() {}},+}).css;++test("reference stylesheet uses the visible container percentage rather than a full-screen viewport unit", () => {+ const css = mobileCSS();+ const referenceRule = css.match(/\.mobile-reference-dialog \.mobile-reference-sheet\s*\{([^}]+)\}/);+ assert.ok(referenceRule);+ assert.match(referenceRule[1], /max-height:\s*60%\s*;/);+ assert.doesNotMatch(referenceRule[1], /(?:min-)?height:\s*\d+(?:d?vh|px)\s*;/);+ assert.match(css, /\.mobile-reference-dialog--compact \.b3-dialog__header\s*\{\s*display:\s*none;/);+});++// Browser verification is opt-in because the regular unit suite also runs in socket-restricted environments.+const chromium = process.env.CHROMIUM_PATH;++test("reference drawer CSS caps its height at 60 percent of the visible viewport", {skip: !chromium}, () => {+ const css = mobileCSS();+ const directory = mkdtempSync(join(tmpdir(), "siyuan-reference-viewport-"));+ try {+ const html = join(directory, "index.html");+ writeFileSync(html, `<style>+ .b3-dialog {display:flex;position:absolute;width:100%}+ .b3-dialog__container {flex-shrink:0}+ ${css}+ </style>+ <div class="mobile-bottom-sheet-dialog mobile-reference-dialog b3-dialog--open">+ <div class="b3-dialog">+ <div class="b3-dialog__container mobile-bottom-sheet mobile-reference-sheet" style="height:60%;width:100vw">+ <div class="b3-dialog__body">Reference content</div>+ </div>+ </div>+ </div>+ <script>+ const container = document.querySelector('.b3-dialog');+ const sheet = document.querySelector('.mobile-reference-sheet');+ const results = [];+ for (const height of [800, 350, 250, 600]) {+ container.style.height = height + 'px';+ container.style.top = '90px';+ const rect = sheet.getBoundingClientRect();+ results.push(rect.height <= height * 0.6 + 1 && rect.height > 0 &&+ rect.bottom <= 90 + height + 1 && rect.top >= 90 + height * 0.4 - 1);+ }+ document.body.setAttribute('data-results', results.join(','));+ </script>`);+ const result = spawnSync(chromium, ["--headless", "--no-sandbox", "--disable-dev-shm-usage",+ "--disable-gpu", "--dump-dom", `--user-data-dir=${join(directory, "profile")}`, `file://${html}`],+ {encoding: "utf8", timeout: 30000, env: {...process.env, HOME: directory, XDG_CONFIG_HOME: directory}});+ assert.equal(result.status, 0, result.error?.message || result.stderr);+ assert.match(result.stdout, /data-results="true,true,true,true"/);+ } finally {+ rmSync(directory, {recursive: true, force: true});+ }+});diff --git a/app/src/mobile/util/openReference.ts b/app/src/mobile/util/openReference.tsnew file mode 100644index 0000000000..4f0d7b95d8--- /dev/null+++ b/app/src/mobile/util/openReference.ts@@ -0,0 +1,244 @@+import {Constants} from "../../constants";+import {Protyle} from "../../protyle";+import {fetchSyncPost} from "../../util/fetch";+import {showMessage} from "../../dialog/message";+import {escapeHtml} from "../../util/escape";+import {bindBottomSheetDialog} from "./bindBottomSheetDialog";+import {MobileEditorDialog} from "./MobileEditorDialog";+import {activeBlur} from "./keyboardToolbar";+import {flushMobileSecondaryEditor, registerMobileSecondaryEditor} from "./secondaryEditors";+import {getVisibleViewportBounds} from "./visibleViewport";+import {getDocByScroll, saveScroll} from "../../protyle/scroll/saveScroll";+import {registerEditorSave} from "../../protyle/util/editorSave";+import {hasAVEditorSession} from "../../protyle/render/av/editorSession";+import {closeAVCellEditor} from "../../protyle/render/av/cellEditor";++interface ReferenceSheet {+ dialog: MobileEditorDialog;+ editor: Protyle;+ source: IProtyle;+ sourceRootID: string;+ sourceNotebookID: string;+ sourceBlockID: string;+ targetRootID: string;+ scrollTop: number;+ scrollLeft: number;+ disposeEditor: () => void;+ flush: () => Promise<void>;+ replace: () => Promise<void>;+}++let current: ReferenceSheet;+let openVersion = 0;++export const invalidateMobileReferenceOpen = () => {+ openVersion++;+};++export const removeMobileReferenceSheet = (options: {notebookId?: string, rootIDs?: string[]}) => {+ if (!options.notebookId && !options.rootIDs?.length) {+ return;+ }+ // 失效尚未完成的加载,避免锁定后迟到的响应重新显示内容。+ openVersion++;+ const sheet = current;+ if (!sheet || !((options.notebookId && [sheet.sourceNotebookID, sheet.editor.protyle.notebookId]+ .includes(options.notebookId)) || options.rootIDs?.some(id =>+ [sheet.sourceRootID, sheet.targetRootID, sheet.editor.protyle.block.rootID].includes(id)))) {+ return;+ }+ current = undefined;+ closeAVCellEditor(sheet.editor.protyle.element, false);+ sheet.disposeEditor();+ sheet.dialog.element.querySelector(".b3-dialog__body").replaceChildren();+ sheet.dialog.discard();+};++export const refreshMobileReferenceSheet = (rootIDs: string[], updateReadonly: boolean) => {+ const sheet = current;+ if (!sheet || !rootIDs.includes(sheet.editor.protyle.block.rootID)) {+ return;+ }+ void sheet.flush().then(() => {+ if (current !== sheet || sheet.dialog.element.hasAttribute("inert")) {+ return;+ }+ getDocByScroll({+ protyle: sheet.editor.protyle,+ scrollAttr: saveScroll(sheet.editor.protyle, true) as IScrollAttr || {+ rootId: sheet.targetRootID,+ zoomInId: sheet.editor.protyle.block.showAll ? sheet.editor.protyle.block.id : undefined,+ scrollTop: sheet.editor.protyle.contentElement.scrollTop,+ },+ updateReadonly,+ isValid: () => current === sheet && !sheet.dialog.element.hasAttribute("inert"),+ });+ }).catch(error => showMessage(escapeHtml(String(error))));+};++export const openMobileReference = async (protyle: IProtyle, blockId: string) => {+ const version = ++openVersion;+ // 嵌套引用替换当前抽屉,始终保留最初的文档及阅读位置。+ const previous = current;+ const origin = previous?.editor.protyle === protyle ? previous : undefined;+ const source = origin?.source || protyle;+ const sourceRootID = origin?.sourceRootID || source.block.rootID;+ const sourceNotebookID = origin?.sourceNotebookID || source.notebookId;+ const sourceBlockID = origin?.sourceBlockID || source.block.id;+ const scrollTop = origin?.scrollTop ?? source.contentElement.scrollTop;+ const scrollLeft = origin?.scrollLeft ?? source.contentElement.scrollLeft;+ const isValid = () => version === openVersion && source.element.isConnected &&+ source.block.rootID === sourceRootID && source.notebookId === sourceNotebookID && source.block.id === sourceBlockID;+ window.siyuan.menus.menu.remove();+ activeBlur(true);+ try {+ const response = await fetchSyncPost("/api/block/getBlockInfo", {id: blockId});+ if (!isValid() || response.code !== 0 || !response.data?.rootID) {+ if (isValid() && response.code > 0) {+ showMessage(response.msg || window.siyuan.languages.refExpired);+ }+ return;+ }+ try {+ await previous?.replace();+ } catch (error) {+ console.error(error);+ return;+ }+ if (!isValid()) {+ return;+ }+ let disposed = false;+ let replacing = false;+ const restoreScroll = () => {+ if (source.element.isConnected && source.block.rootID === sourceRootID &&+ source.notebookId === sourceNotebookID && source.block.id === sourceBlockID) {+ source.contentElement.scrollTop = scrollTop;+ source.contentElement.scrollLeft = scrollLeft;+ }+ };+ const dialog = new MobileEditorDialog({+ title: window.siyuan.languages.viewRefContent,+ content: '<div class="mobile-reference-editor fn__flex-1"></div>',+ width: "100vw",+ height: "60%",+ containerClassName: "mobile-reference-sheet",+ destroyCallback: () => {+ disposeSheet();+ window.removeEventListener("resize", resize);+ sheet.disposeEditor();+ if (current === sheet) {+ current = undefined;+ }+ restoreScroll();+ },+ });+ dialog.element.classList.add("mobile-reference-dialog");+ const editor = new Protyle(protyle.app, dialog.element.querySelector(".mobile-reference-editor"), {+ blockId,+ rootId: response.data.rootID,+ notebookId: response.data.box,+ databaseAttr: true,+ action: [blockId === response.data.rootID ? Constants.CB_GET_CONTEXT : Constants.CB_GET_ALL],+ render: {+ scroll: true,+ gutter: true,+ breadcrumb: false,+ title: blockId === response.data.rootID,+ background: false,+ },+ typewriterMode: false,+ });+ const saveGuard = registerEditorSave(editor.protyle);+ const childWaiters = new Set<() => void>();+ const waitForChildEditor = () => {+ if (disposed || !hasAVEditorSession(editor.protyle.element)) {+ return Promise.resolve();+ }+ // 富文本单元格使用自己的确认按钮,保持浮层可操作,等待其提交或取消后再关闭抽屉。+ return new Promise<void>(resolve => {+ const finish = () => {+ if (!disposed && hasAVEditorSession(editor.protyle.element)) {+ return;+ }+ editor.protyle.element.removeEventListener("av-editor-close", finish);+ childWaiters.delete(finish);+ resolve();+ };+ childWaiters.add(finish);+ editor.protyle.element.addEventListener("av-editor-close", finish);+ });+ };+ const sheet: ReferenceSheet = {dialog, editor, source, sourceRootID, sourceNotebookID, sourceBlockID,+ targetRootID: response.data.rootID, scrollTop, scrollLeft,+ replace: async () => {+ replacing = true;+ try {+ await dialog.close();+ } finally {+ replacing = false;+ }+ },+ flush: async () => {+ await waitForChildEditor();+ if (disposed) {+ return;+ }+ closeAVCellEditor(editor.protyle.element);+ editor.protyle.title?.flushPendingInput();+ await flushMobileSecondaryEditor(editor);+ await saveGuard.flush();+ },+ disposeEditor: () => {+ if (!disposed) {+ disposed = true;+ childWaiters.forEach(finish => finish());+ editor.protyle.title?.cancelPendingInput();+ saveGuard.dispose();+ editor.destroy();+ }+ }};+ current = sheet;+ registerMobileSecondaryEditor(editor, () => removeMobileReferenceSheet({rootIDs: [sheet.targetRootID]}));+ dialog.beforeClose = async () => {+ if (!replacing) {+ invalidateMobileReferenceOpen();+ }+ await waitForChildEditor();+ if (disposed) {+ return;+ }+ if (editor.isUploading()) {+ throw new Error(window.siyuan.languages.uploading);+ }+ if (dialog.element.contains(document.activeElement)) {+ activeBlur(true);+ }+ dialog.element.setAttribute("inert", "");+ try {+ await sheet.flush();+ } catch (error) {+ dialog.element.removeAttribute("inert");+ throw error;+ }+ sheet.disposeEditor();+ if (current === sheet) {+ current = undefined;+ }+ };+ dialog.register();+ const resize = () => {+ const viewport = getVisibleViewportBounds();+ const container = dialog.element.querySelector<HTMLElement>(".b3-dialog");+ container.style.top = `${viewport.top}px`;+ container.style.height = `${viewport.bottom - viewport.top}px`;+ dialog.element.classList.toggle("mobile-reference-dialog--compact", viewport.bottom - viewport.top < 400);+ restoreScroll();+ };+ const disposeSheet = bindBottomSheetDialog(dialog, () => dialog.close(), resize);+ window.addEventListener("resize", resize);+ resize();+ } catch (error) {+ showMessage(escapeHtml(String(error)));+ }+};diff --git a/app/src/protyle/header/Title.ts b/app/src/protyle/header/Title.tsindex a7089005b4..4f6858f1e2 100644--- a/app/src/protyle/header/Title.ts+++ b/app/src/protyle/header/Title.ts@@ -38,8 +38,10 @@ export class Title {public element: HTMLElement;public editElement: HTMLElement;private timeout: number;+ private pendingRename?: () => void;+ private composing = false;- constructor(protyle: IProtyle) {+ constructor(private protyle: IProtyle) {this.element = document.createElement("div");this.element.className = "protyle-title";if (window.siyuan.config.editor.displayBookmarkIcon) {@@ -80,6 +82,7 @@ export class Title {});this.editElement.addEventListener("input", (event: InputEvent) => {if (event.isComposing) {+ this.composing = true;return;}if (this.editElement.textContent === "") {@@ -90,6 +93,7 @@ export class Title {this.rename(protyle);});this.editElement.addEventListener("compositionend", () => {+ this.composing = false;this.rename(protyle);});this.editElement.addEventListener("drop", (event: DragEvent) => {@@ -343,6 +347,7 @@ export class Title {private rename(protyle: IProtyle) {clearTimeout(this.timeout);+ this.pendingRename = undefined;if (!validateName(this.editElement.textContent, this.editElement)) {// 字数过长会导致滚动const offset = getSelectionOffset(this.editElement);@@ -351,7 +356,9 @@ export class Title {return false;}hideTooltip();- this.timeout = window.setTimeout(() => {+ this.pendingRename = () => {+ this.pendingRename = undefined;+ this.timeout = undefined;const fileName = replaceFileName(this.editElement.textContent);fetchPost("/api/filetree/renameDoc", {notebook: protyle.notebookId,@@ -363,7 +370,24 @@ export class Title {this.setTitle(fileName);focusByOffset(this.editElement, offset.start, offset.end);}- }, Constants.TIMEOUT_INPUT);+ };+ this.timeout = window.setTimeout(this.pendingRename, Constants.TIMEOUT_INPUT);+ }++ public flushPendingInput() {+ if (this.composing) {+ this.rename(this.protyle);+ }+ const rename = this.pendingRename;+ this.cancelPendingInput();+ rename?.();+ }++ public cancelPendingInput() {+ clearTimeout(this.timeout);+ this.timeout = undefined;+ this.pendingRename = undefined;+ this.composing = false;}public setTitle(title: string, empty = false) {diff --git a/app/src/protyle/index.ts b/app/src/protyle/index.tsindex 0d56b1e5ed..c5a2a4772c 100644--- a/app/src/protyle/index.ts+++ b/app/src/protyle/index.ts@@ -124,6 +124,7 @@ export class Protyle {public readonly version: string;public protyle: IProtyle;+ private destroyed = false;/*** @param id 要挂载 Protyle 的元素或者元素 ID。@@ -561,11 +562,15 @@ export class Protyle {getDocParam.notebook = this.protyle.notebookId;}fetchPost("/api/filetree/getDoc", getDocParam, getResponse => {+ if (this.destroyed) {+ return;+ }onGet({data: getResponse,protyle: this.protyle,action: mergedOptions.action,scrollPosition: mergedOptions.scrollPosition,+ isValid: () => !this.destroyed,afterCB: () => {this.afterOnGet(mergedOptions);}@@ -666,6 +671,7 @@ export class Protyle {/** 销毁编辑器 */public destroy() {+ this.destroyed = true;/// #if MOBILEunregisterMobileSecondaryEditor(this);/// #endifdiff --git a/app/src/protyle/render/av/cellEditor.ts b/app/src/protyle/render/av/cellEditor.tsindex 225dfb723c..cbc6690d90 100644--- a/app/src/protyle/render/av/cellEditor.ts+++ b/app/src/protyle/render/av/cellEditor.ts@@ -1,7 +1,16 @@export const AV_CELL_EDITOR_CLOSE_EVENT = "siyuan-av-cell-editor-close";-export const closeAVCellEditor = () => {- document.querySelectorAll(".av__mask:not(.av__richtext-mask)").forEach(element => {+export const closeAVCellEditor = (owner?: HTMLElement, save = true) => {+ document.querySelectorAll<HTMLElement>(save ? ".av__mask:not(.av__richtext-mask)" : ".av__mask").forEach(element => {+ if (owner && !Array.from(owner.querySelectorAll<HTMLElement>("[data-node-id]"))+ .some(block => block.dataset.nodeId === element.dataset.avBlockId)) {+ return;+ }+ if (!save) {+ // 锁定或删除所属内容时立即清除浮层,不再向已失效的目标提交草稿。+ element.remove();+ return;+ }// 先结束输入法组合输入,再由编辑器提交原单元格的值。if (element.contains(document.activeElement)) {(document.activeElement as HTMLElement).blur();diff --git a/app/src/protyle/toolbar/templatePreview.test.ts b/app/src/protyle/toolbar/templatePreview.test.tsindex b0c86c7402..35e6d33c6b 100644--- a/app/src/protyle/toolbar/templatePreview.test.ts+++ b/app/src/protyle/toolbar/templatePreview.test.ts@@ -6,6 +6,7 @@ import {runInNewContext} from "node:vm";import * as ts from "typescript";import {withFetchTimeout} from "../../util/fetchTimeout";import {trackSettingRequest} from "../../config/setting/pending";+import {trackEditorSaveRequest} from "../util/editorSave";const loadPreview = () => {const requests: Array<{resolve: (response: Response) => void, reject: (error: Error) => void}> = [];@@ -34,6 +35,7 @@ const loadPreview = () => {"./processMessage": messagesModule,"./fetchTimeout": {withFetchTimeout},"../config/setting/pending": {trackSettingRequest},+ "../protyle/util/editorSave": {trackEditorSaveRequest},});const previewModule = loadModule("util.ts", {"../../util/fetch": fetchModule,diff --git a/app/src/protyle/util/editorSave.test.ts b/app/src/protyle/util/editorSave.test.tsnew file mode 100644index 0000000000..d868d8cfac--- /dev/null+++ b/app/src/protyle/util/editorSave.test.ts@@ -0,0 +1,214 @@+import * as assert from "node:assert/strict";+import {test} from "node:test";+import {readFileSync} from "node:fs";+import {join} from "node:path";+import {runInNewContext} from "node:vm";+import * as ts from "typescript";+import {registerEditorSave, trackEditorSaveRequest} from "./editorSave";++const source = (path: string) => ts.transpileModule(readFileSync(join(__dirname, path), "utf8"), {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},+}).outputText;++const loadFetch = (fetchImplementation: typeof fetch) => {+ const exports: {fetchPost?: (...args: any[]) => Promise<void>, fetchSyncPost?: (...args: any[]) => Promise<unknown>} = {};+ runInNewContext(source("../../util/fetch.ts"), {+ exports,+ require: (name: string) => {+ switch (name) {+ case "./fetchWithAppId": return {fetchWithAppId: fetchImplementation};+ case "../constants": return {Constants: {}};+ case "electron": return {ipcRenderer: {send: () => {}}};+ case "./processMessage": return {processMessage: (response: {code: number}) => response.code >= 0};+ case "./kernelFault": return {kernelError: () => {}};+ case "../config/setting/pending": return {trackSettingRequest: (_url: string, promise: Promise<unknown>) => promise};+ case "../protyle/util/editorSave": return {trackEditorSaveRequest};+ case "./fetchTimeout": return {withFetchTimeout: (request: () => Promise<unknown>) => request()};+ default: throw new Error(name);+ }+ },+ FormData,+ window: {siyuan: {}},+ console: {warn: () => {}},+ });+ return exports;+};++const editor = () => {+ Object.assign(globalThis, {window: {siyuan: {languages: {settingsPendingSaveError: "Save failed"}}}});+ return {id: "drawer", path: "/root.sy", notebookId: "box"} as IProtyle;+};+const request = (session = "drawer", action = "update", id = "block") => ({+ session,+ transactions: [{doOperations: [{action, id, data: "<div>latest content</div>"}]}],+});+const success = {code: 0, data: [{doOperations: [{action: "update"}]}]};+const response = (data: unknown) => new Response(JSON.stringify(data), {headers: {"Content-Type": "application/json"}});++test("tracks actual fetchPost business, network, HTTP and malformed save failures despite swallowed errors", async () => {+ for (const failure of ["negative", "positive", "network", "http", "missing-result", "missing-operations"]) {+ const guard = registerEditorSave(editor());+ try {+ const {fetchPost} = loadFetch(async () => {+ if (failure === "network") throw new Error("Failed to fetch");+ if (failure === "http") return new Response(null, {status: 403});+ if (failure === "missing-result") return response({code: 0, data: []});+ if (failure === "missing-operations") return response({code: 0, data: [{}]});+ return response({code: failure === "positive" ? 1 : -1, data: null});+ });+ await fetchPost("/api/transactions", request());+ await assert.rejects(guard.flush(), /Save failed/, failure);+ } finally {+ guard.dispose();+ }+ }+});++test("waits for an actual pending successful transaction response", async () => {+ const guard = registerEditorSave(editor());+ let finish: (value: Response) => void;+ const {fetchPost} = loadFetch(() => new Promise(resolve => finish = resolve));+ const saving = fetchPost("/api/transactions", request());+ let flushed = false;+ const flushing = guard.flush().then(() => flushed = true);+ await Promise.resolve();+ assert.equal(flushed, false);+ finish(response(success));+ await Promise.all([saving, flushing]);+ assert.equal(flushed, true);+ guard.dispose();+});++test("only watches registered sessions and matching notebook/path title saves", async () => {+ const guard = registerEditorSave(editor());+ const {fetchPost} = loadFetch(async () => response({code: -1, data: null}));+ try {+ await fetchPost("/api/transactions", request("main"));+ await fetchPost("/api/filetree/renameDoc", {notebook: "other", path: "/root.sy", title: "title"});+ await fetchPost("/api/filetree/renameDoc", {notebook: "box", path: "/other.sy", title: "title"});+ await guard.flush();+ await fetchPost("/api/filetree/renameDoc", {notebook: "box", path: "/root.sy", title: "title"});+ await assert.rejects(guard.flush(), /Save failed/);+ } finally {+ guard.dispose();+ }+});++test("fetchSyncPost failures are observed before response handling", async () => {+ const guard = registerEditorSave(editor());+ const {fetchSyncPost} = loadFetch(async () => response({code: -1, data: null}));+ try {+ await fetchSyncPost("/api/transactions", request());+ await assert.rejects(guard.flush(), /Save failed/);+ } finally {+ guard.dispose();+ }+});++test("only a later successful full update of the same block clears its earlier failed update", async () => {+ const guard = registerEditorSave(editor());+ let payload: unknown = {code: -1, data: null};+ const {fetchPost} = loadFetch(async () => response(payload));+ try {+ await fetchPost("/api/transactions", request());+ payload = success;+ await fetchPost("/api/transactions", request("drawer", "update", "other-block"));+ await assert.rejects(guard.flush(), /Save failed/);+ await fetchPost("/api/transactions", request());+ await guard.flush();+ } finally {+ guard.dispose();+ }+});++test("later title saves can resolve failed renames without replaying any request", async () => {+ const guard = registerEditorSave(editor());+ let failed = true;+ let requests = 0;+ const {fetchPost} = loadFetch(async () => {+ requests++;+ return response({code: failed ? -1 : 0, data: null});+ });+ try {+ const rename = {notebook: "box", path: "/root.sy", title: "latest title"};+ await fetchPost("/api/filetree/renameDoc", rename);+ await assert.rejects(guard.flush(), /Save failed/);+ failed = false;+ await fetchPost("/api/filetree/renameDoc", rename);+ await guard.flush();+ assert.equal(requests, 2);+ } finally {+ guard.dispose();+ }+});++test("ambiguous structural failures stay blocked after later successful edits and are never replayed", async () => {+ const guard = registerEditorSave(editor());+ let failed = true;+ let requests = 0;+ const {fetchPost} = loadFetch(async () => {+ requests++;+ if (failed) throw new Error("offline");+ return response(success);+ });+ try {+ await fetchPost("/api/transactions", request("drawer", "insert"));+ failed = false;+ await fetchPost("/api/transactions", request());+ await assert.rejects(guard.flush(), /Save failed/);+ await assert.rejects(guard.flush(), /Save failed/);+ assert.equal(requests, 2);+ } finally {+ guard.dispose();+ }+});++test("disposal drops failure state and ignores late requests after lock or destruction", async () => {+ const guard = registerEditorSave(editor());+ let finish: (value: Response) => void;+ const {fetchPost} = loadFetch(() => new Promise(resolve => finish = resolve));+ const saving = fetchPost("/api/transactions", request());+ guard.dispose();+ finish(response({code: -1, data: null}));+ await saving;+ await guard.flush();+});++test("Title flushes debounce once, captures composition, and can cancel pending saves", () => {+ let nextTimer = 0;+ const timers = new Map<number, () => void>();+ const requests: unknown[] = [];+ const exports: {Title?: {prototype: any}} = {};+ runInNewContext(source("../header/Title.ts"), {+ exports,+ require: (name: string) => {+ if (name === "../../util/fetch") return {fetchPost: (_url: string, data: unknown) => requests.push(data)};+ if (name === "../../editor/rename") return {validateName: () => true, replaceFileName: (name: string) => name};+ if (name === "../../dialog/tooltip") return {hideTooltip: () => {}};+ if (name === "../../constants") return {Constants: {TIMEOUT_INPUT: 400}};+ return {};+ },+ window: {setTimeout: (callback: () => void) => {timers.set(++nextTimer, callback); return nextTimer;}},+ clearTimeout: (timer: number) => timers.delete(timer),+ });+ const title = Object.create(exports.Title.prototype);+ const protyle = editor();+ title.protyle = protyle;+ title.editElement = {textContent: "new title"};+ title.rename(protyle);+ assert.equal(timers.size, 1);+ title.flushPendingInput();+ title.flushPendingInput();+ assert.equal(timers.size, 0);+ assert.equal(requests.length, 1);+ title.editElement.textContent = "composing title";+ title.composing = true;+ title.flushPendingInput();+ assert.equal(requests.length, 2);+ assert.equal((requests[1] as {title: string}).title, "composing title");+ title.rename(protyle);+ title.cancelPendingInput();+ title.flushPendingInput();+ assert.equal(timers.size, 0);+ assert.equal(requests.length, 2);+});diff --git a/app/src/protyle/util/editorSave.ts b/app/src/protyle/util/editorSave.tsnew file mode 100644index 0000000000..2781cfed80--- /dev/null+++ b/app/src/protyle/util/editorSave.ts@@ -0,0 +1,81 @@+interface EditorSaveRecord {+ pending: Set<Promise<void>>;+ results: Map<string, {version: number, failed: boolean}>;+ version: number;+ failedStructure: boolean;+ disposed: boolean;+}++const editors = new Map<IProtyle, EditorSaveRecord>();++// 仅由需要确认保存结果后才能销毁的编辑器启用,不改变普通请求的错误处理。+export const registerEditorSave = (protyle: IProtyle) => {+ const record: EditorSaveRecord = {+ pending: new Set(), results: new Map(), version: 0, failedStructure: false, disposed: false,+ };+ editors.set(protyle, record);+ return {+ flush: async () => {+ while (!record.disposed && record.pending.size) {+ await Promise.all([...record.pending]);+ }+ if (!record.disposed && (record.failedStructure || [...record.results.values()].some(result => result.failed))) {+ throw new Error(window.siyuan.languages.settingsPendingSaveError);+ }+ },+ dispose: () => {+ record.disposed = true;+ record.pending.clear();+ record.results.clear();+ record.failedStructure = false;+ if (editors.get(protyle) === record) {+ editors.delete(protyle);+ }+ },+ };+};++export const trackEditorSaveRequest = <T>(url: string, data: any, promise: Promise<T>): Promise<T> => {+ if (!editors.size || (url !== "/api/transactions" && url !== "/api/filetree/renameDoc")) {+ return promise;+ }+ const transactions = url === "/api/transactions";+ // 只保存目标 ID 和结果,不保留块 HTML、标题或可重放的请求数据。+ const transactionList = transactions && Array.isArray(data?.transactions) ? data.transactions : [];+ const operations = transactionList.flatMap((item: {doOperations?: IOperation[]}) =>+ Array.isArray(item?.doOperations) ? item.doOperations : []);+ const keys: string[] = transactions ? operations.length && operations.every((item: IOperation) =>+ item?.action === "update" && item.id && typeof item.data === "string") ?+ [...new Set<string>(operations.map((item: IOperation) => `block:${item.id}`))] : [] : ["title"];+ const transactionCount = transactionList.length;+ editors.forEach((record, protyle) => {+ if (transactions ? data?.session !== protyle.id :+ !protyle.path || !protyle.notebookId || data?.path !== protyle.path || data?.notebook !== protyle.notebookId) {+ return;+ }+ const version = ++record.version;+ const complete = (failed: boolean) => {+ if (record.disposed) {+ return;+ }+ if (!keys.length) {+ // 结构操作的结果不明确时禁止自动重放,也不能用之后的文本保存覆盖其失败状态。+ record.failedStructure ||= failed;+ } else {+ keys.forEach(key => {+ if ((record.results.get(key)?.version || 0) < version) {+ record.results.set(key, {version, failed});+ }+ });+ }+ };+ const pending = promise.then((response: any) => {+ complete(response?.code !== 0 || (transactions && (!transactionCount ||+ !Array.isArray(response.data) || response.data.length !== transactionCount ||+ response.data.some((item: {doOperations?: IOperation[]}) => !Array.isArray(item?.doOperations)))));+ }, () => complete(true));+ record.pending.add(pending);+ void pending.then(() => record.pending.delete(pending));+ });+ return promise;+};diff --git a/app/src/template/manager.ts b/app/src/template/manager.tsindex 1e76d76c25..236be4bfff 100644--- a/app/src/template/manager.ts+++ b/app/src/template/manager.ts@@ -19,7 +19,7 @@ import {openModel} from "../mobile/menu/model";import {closeModel} from "../mobile/util/closePanel";import {loadMobileFileById} from "../mobile/editor";import {MenuItem} from "../menus/Menu";-import {closeMobileBacklinkSheets} from "../mobile/util/backlinkPanels";+import {closeMobileEditorSheets} from "../mobile/util/MobileEditorDialog";import {Constants} from "../constants";import {setStorageVal} from "../protyle/util/compatibility";import {isEncryptedBox} from "../util/pathName";@@ -451,7 +451,7 @@ ${canOpenFolder ? button("open", lang.showInFolder) : ""}return;}if (mobile) {- await closeMobileBacklinkSheets();+ await closeMobileEditorSheets();if (closed) {return;}diff --git a/app/src/util/fetch.test.ts b/app/src/util/fetch.test.tsindex 0c432f2ed4..71b27ddea6 100644--- a/app/src/util/fetch.test.ts+++ b/app/src/util/fetch.test.ts@@ -6,6 +6,7 @@ import {runInNewContext} from "node:vm";import * as ts from "typescript";import {withFetchTimeout} from "./fetchTimeout";import {flushSettingSaves, settingSaveFailures, trackSettingRequest} from "../config/setting/pending";+import {trackEditorSaveRequest} from "../protyle/util/editorSave";const loadFetchPost = (fetchImplementation: typeof fetch = () => new Promise(() => {}),processResponse: (response: IWebSocketData) => boolean = () => true) => {@@ -28,6 +29,7 @@ const loadFetchPost = (fetchImplementation: typeof fetch = () => new Promise(()case "./processMessage": return {processMessage: processResponse};case "./kernelFault": return {kernelError: () => assert.fail("unexpected kernel error")};case "../config/setting/pending": return {trackSettingRequest};+ case "../protyle/util/editorSave": return {trackEditorSaveRequest};case "./fetchTimeout": return {withFetchTimeout: (request: (signal?: AbortSignal) => Promise<unknown>, signal: AbortSignal, timeout: number) => {timeouts.push(timeout);diff --git a/app/src/util/fetch.ts b/app/src/util/fetch.tsindex c7a5d84864..ca50be44a4 100644--- a/app/src/util/fetch.ts+++ b/app/src/util/fetch.ts@@ -8,6 +8,7 @@ import {kernelError} from "./kernelFault";import {withFetchTimeout} from "./fetchTimeout";import type {FetchGet, FetchPost, FetchSyncPost} from "../types/api";import {trackSettingRequest} from "../config/setting/pending";+import {trackEditorSaveRequest} from "../protyle/util/editorSave";export const fetchPost = ((url: string,@@ -47,7 +48,7 @@ export const fetchPost = ((init.signal = signal;}let isGetFile202 = false;- return trackSettingRequest(url, withFetchTimeout((requestSignal) => fetchWithAppId(url, {...init, signal: requestSignal}).then((response) => {+ return trackEditorSaveRequest(url, data, trackSettingRequest(url, withFetchTimeout((requestSignal) => fetchWithAppId(url, {...init, signal: requestSignal}).then((response) => {switch (response.status) {case 403:case 404:@@ -77,7 +78,7 @@ export const fetchPost = ((return response.text();}}- }), signal, timeout)).then((response: IWebSocketData) => {+ }), signal, timeout))).then((response: IWebSocketData) => {if (failCallback && url === "/api/file/getFile" && isGetFile202) {failCallback(response);return;@@ -143,8 +144,8 @@ export const fetchSyncPost = (async (url: string, data?: any, headers?: Record<sinit.body = JSON.stringify(data);}}- return trackSettingRequest(url, fetchWithAppId(url, init).then(async res => {- const res2 = await res.json() as IWebSocketData;+ return trackSettingRequest(url, trackEditorSaveRequest(url, data,+ fetchWithAppId(url, init).then(res => res.json() as Promise<IWebSocketData>)).then(res2 => {if (process) {processMessage(res2);}diff --git a/app/src/util/fetchWithAppId.test.ts b/app/src/util/fetchWithAppId.test.tsindex a52f006561..4211214ba9 100644--- a/app/src/util/fetchWithAppId.test.ts+++ b/app/src/util/fetchWithAppId.test.ts@@ -5,6 +5,7 @@ import {runInNewContext} from "node:vm";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";import {SIYUAN_APP_ID_HEADER, withAPIAppId} from "./fetchAppId";import {ContractFormData} from "./contractFormData";+import {trackEditorSaveRequest} from "../protyle/util/editorSave";const load = (path: string, globals: Record<string, unknown>, dependencies: Record<string, unknown>) => {const exports = {};@@ -61,6 +62,7 @@ test("shared fetch helpers attach the caller and preserve payloads", async () =>"./kernelFault": {kernelError: () => assert.fail("Unexpected kernel error")},"./fetchTimeout": {withFetchTimeout: (run: (signal: AbortSignal) => unknown, signal: AbortSignal) => run(signal)},"../config/setting/pending": {trackSettingRequest: (_url: string, promise: Promise<unknown>) => promise},+ "../protyle/util/editorSave": {trackEditorSaveRequest},}) as typeof import("./fetch");const signal = new AbortController().signal;const headers = Object.freeze({Authorization: "Token test"});diff --git a/app/src/util/reloadSync.ts b/app/src/util/reloadSync.tsindex ffc0e7adf5..dbde0138ab 100644--- a/app/src/util/reloadSync.ts+++ b/app/src/util/reloadSync.ts@@ -12,6 +12,7 @@ import type {Tab} from "../layout/Tab";import {setTitle} from "./processTitle";/// #if MOBILEimport {getMobileBacklinkPanels, removeMobileBacklinkContent} from "../mobile/util/backlinkPanels";+import {refreshMobileReferenceSheet, removeMobileReferenceSheet} from "../mobile/util/openReference";/// #endif/// #if !MOBILEimport {removeBlockPanelEditors} from "../block/panelRemoval";@@ -31,6 +32,8 @@ export const reloadSync = (}/// #if MOBILEremoveMobileBacklinkContent({rootIDs: data.removeRootIDs});+ removeMobileReferenceSheet({rootIDs: data.removeRootIDs});+ refreshMobileReferenceSheet(data.upsertRootIDs, updateReadonly);getMobileBacklinkPanels().forEach(panel => {panel.markIndexDirty({backlinkChanged: true, backlinkFull: true});panel.refreshAfterIndex();diff --git a/app/tests/mobileBacklinks.test.js b/app/tests/mobileBacklinks.test.jsindex 4d2b316ada..551528e3c9 100644--- a/app/tests/mobileBacklinks.test.js+++ b/app/tests/mobileBacklinks.test.js@@ -10,7 +10,7 @@ const sources = () => {for (const name of ["layout/dock/BacklinkContent", "layout/dock/backlinkRefresh","layout/dock/GlobalBacklinkList", "layout/dock/globalBacklinkPaging","layout/dock/backlinkReadingAnchor", "layout/dock/backlinkSourceFilter", "mobile/util/secondaryEditors",- "mobile/util/backlinkPanels", "mobile/util/openBacklinks", "mobile/util/bindBottomSheetDrag", "mobile/util/bindBottomSheetDialog", "menus/sheetOpen", "protyle/util/transactionQueue",+ "mobile/util/backlinkPanels", "mobile/util/openBacklinks", "mobile/util/MobileEditorDialog", "mobile/util/bindBottomSheetDrag", "mobile/util/bindBottomSheetDialog", "menus/sheetOpen", "protyle/util/transactionQueue","util/escape", "util/zIndex", "dialog/index", "layout/dock/panelSearch", "protyle/wysiwyg/backlinkTypeFold","layout/dock/backlinkMentionCache", "layout/dock/bottomBacklinkScroll"]) {modules[name] = ts.transpileModule(preprocess(@@ -286,7 +286,7 @@ const runCases = async (sources) => {sheet.editors.push(sheetEditor);registry.registerMobileSecondaryEditor(sheetEditor, noop);sheetEditor.protyle.wysiwyg.flushPendingInput = () => save;- const closing = panels.closeMobileBacklinkSheets();+ const closing = load("mobile/util/MobileEditorDialog").closeMobileEditorSheets();await tick();assert.equal(sheetEditor.destroyed, undefined, "sheet must remain mounted until pending input completes");finishSave();diff --git a/app/tests/templateManager.test.js b/app/tests/templateManager.test.jsindex 1632812940..551c1ada90 100644--- a/app/tests/templateManager.test.js+++ b/app/tests/templateManager.test.js@@ -79,7 +79,7 @@ const runCases = async (sources, css, mobile, legacyMobile) => {opened.push(id);if (openSucceeded) {afterOpen({notebookId: "notebook"});} else {onFailure();}}},- "mobile/util/backlinkPanels": {closeMobileBacklinkSheets: async () => {}},+ "mobile/util/MobileEditorDialog": {closeMobileEditorSheets: async () => {}},"constants": {Constants: {LOCAL_DOCINFO: "docInfo"}},"protyle/util/compatibility": {setStorageVal() {}},"util/pathName": {isEncryptedBox: () => false},