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 bottom backlinks on mobile https://github.com/siyuan-note/siyuan/issues/20756
Daniel5b77fe34a899
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i.syindex d93c34cad4..b9fb3032a9 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i.sy@@ -7,7 +7,7 @@"id": "20210808180303-h361q1i","title": "Editor","type": "doc",- "updated": "20261012014930"+ "updated": "20261020212341"},"Children": [{@@ -433,6 +433,71 @@"Data": "In custom profiles, use the category selector to switch between the toolbar and slash menu. Drag the six-dot handle on the left of an item to change its order, or use its switch to change visibility. Drag near the list edge to scroll. Clear the search before sorting, and confirm to save the profile. Built-in profiles are read-only; duplicate one to customize it, then activate the saved profile. Profiles are stored on this device and are not synced across devices. New custom profiles based on Simple or Full follow future visibility defaults for entries you have not changed. An entry you toggle remains an explicit choice. Existing profiles retain their original visibility behavior; copying a profile or creating one based on Current preserves its inheritance and explicit choices. New profiles based on Simple or Full follow the default order as versions change until you customize a level. Based on Current and duplicate preserve existing custom orders. Clear the search and use the reset icon in a column or dock group title to reset that level. To reset every level, use the refresh icon labeled Reset all orders on the right of the Position column title on desktop, or the Reset all orders button at the bottom on mobile. Confirm to save; Cancel discards the changes. Resetting order preserves visibility and dock placement, and reset levels continue to follow future default order changes."}]+ },+ {+ "ID": "20261020212341-1sz2i9r",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20261020212341-1sz2i9r",+ "updated": "20261020212341"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Backlinks at the bottom of documents"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20261020212341-idextig",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261020212341-idextig",+ "updated": "20261020212341"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "On desktop and mobile, enable "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Settings"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Editor"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Bidirectional Links"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Show the backlinks panel at the bottom of the document"+ },+ {+ "Type": "NodeText",+ "Data": " to view backlinks and mentions at the end of the document. The panel loads as you approach it. It appears after the end of the document is loaded and is hidden when there are no results."+ }+ ]}]}diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k.syindex f6ba369168..64dc3fce0b 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k.sy@@ -7,7 +7,7 @@"id": "20210808180320-abz7w6k","title": "编辑器","type": "doc",- "updated": "20261012014930"+ "updated": "20261020212341"},"Children": [{@@ -436,6 +436,71 @@"Data": "编辑自定义方案时,可通过分类选择框切换工具栏与斜杠菜单。拖动项目左侧的六点手柄调整顺序,使用项目开关调整显隐;拖至列表边缘可滚动。排序前需清空搜索,修改后确认保存方案。内置方案只读,可复制后自定义,再启用保存的方案。方案保存在本设备,不跨设备同步。基于简洁或完整创建的新自定义方案,未修改过的入口显隐会跟随后续版本的默认值;手动切换过的入口保留用户选择。旧方案保持原有显隐行为,复制方案或基于当前方案创建时保留其继承方式和明确选择。基于简洁或完整创建的新方案,其未自定义的层级排序会随版本默认顺序更新;基于当前创建或复制方案会保留已有自定义排序。清空搜索后,可点击列标题或停靠栏分组标题上的重置图标重置该层级。重置全部排序时,桌面端可点击“位置”列标题右侧的刷新图标,提示为“重置全部排序”;移动端可点击底部的重置全部排序按钮。确认后保存,取消则放弃修改。重置排序会保留显隐和停靠栏入口所在位置,重置后的层级持续跟随后续版本的默认排序。"}]+ },+ {+ "ID": "20261020212341-tm2junw",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20261020212341-tm2junw",+ "updated": "20261020212341"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "文档底部反链"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20261020212341-af4kmxc",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261020212341-af4kmxc",+ "updated": "20261020212341"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "桌面端和移动端均可在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "设置"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "编辑器"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "双向链接"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "在文档底部显示反链面板"+ },+ {+ "Type": "NodeText",+ "Data": " 中启用此功能,在文档末尾查看反链和提及。面板在接近时加载,正文末尾加载完成后才会显示,无结果时自动隐藏。"+ }+ ]}]}diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2.syindex 33151fab32..3406aa9b45 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2.sy@@ -7,7 +7,7 @@"id": "20211226120854-dr1jfx2","title": "編輯器","type": "doc",- "updated": "20261012014930"+ "updated": "20261020212341"},"Children": [{@@ -408,6 +408,71 @@"Data": "編輯自訂方案時,可透過分類選擇框切換工具列與斜線選單。拖曳項目左側的六點把手調整順序,使用項目開關調整顯隱;拖至清單邊緣可捲動。排序前需清空搜尋,修改後確認儲存方案。內建方案唯讀,可複製後自訂,再啟用儲存的方案。方案儲存在本裝置,不跨裝置同步。基於簡潔或完整建立的新自訂方案,未修改過的入口顯隱會跟隨後續版本的預設值;手動切換過的入口保留使用者選擇。舊方案保持原有顯隱行為,複製方案或基於目前方案建立時保留其繼承方式和明確選擇。基於簡潔或完整建立的新方案,其未自訂的層級排序會隨版本預設順序更新;基於目前方案建立或複製方案會保留既有自訂排序。清空搜尋後,可點擊欄標題或停靠欄分組標題上的重設圖示重設該層級。重設全部排序時,桌面端可點擊「位置」欄標題右側的重新整理圖示,提示為「重設全部排序」;行動端可點擊底部的重設全部排序按鈕。確認後儲存,取消則放棄修改。重設排序會保留顯隱和停靠欄入口所在位置,重設後的層級持續跟隨後續版本的預設排序。"}]+ },+ {+ "ID": "20261020212341-t4poa9r",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20261020212341-t4poa9r",+ "updated": "20261020212341"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "文件底部反向連結"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20261020212341-jm2bq0l",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261020212341-jm2bq0l",+ "updated": "20261020212341"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "桌面端和行動端皆可在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "編輯器"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "雙向連結"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "在文件底部顯示反向連結面板"+ },+ {+ "Type": "NodeText",+ "Data": " 中啟用此功能,在文件末尾查看反向連結和提及。面板在接近時載入,正文末尾載入完成後才會顯示,沒有結果時自動隱藏。"+ }+ ]}]}diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79.syindex b34f2fd8b4..4c255faa40 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79.sy@@ -8,7 +8,7 @@"id": "20240530101000-hnu6o79","title": "エディタ","type": "doc",- "updated": "20261012014930"+ "updated": "20261020212341"},"Children": [{@@ -437,6 +437,71 @@"Data": "カスタムプロファイルでは、分類の選択欄でツールバーとスラッシュメニューを切り替えます。項目の左側にある6つの点のハンドルをドラッグして順序を変更し、スイッチで表示・非表示を設定します。リストの端までドラッグするとスクロールします。並べ替える前に検索欄を空にし、変更後は確認してプロファイルを保存します。組み込みプロファイルは読み取り専用です。複製してカスタマイズし、保存したプロファイルを有効にしてください。プロファイルはこの端末に保存され、端末間では同期されません。シンプルまたは完全を基に作成した新しいカスタムプロファイルでは、変更していない項目の表示・非表示は今後のバージョンの初期値に従います。手動で切り替えた項目は、その選択を維持します。既存のプロファイルは従来の表示動作を維持し、複製または現在の設定を基に作成する場合は、継承方法と明示的な選択を引き継ぎます。シンプルまたは完全を基に作成した新しいプロファイルでは、カスタマイズしていない階層の並び順はバージョンごとの初期順序に従います。現在の設定を基に作成する場合や複製する場合は、既存のカスタム順序を引き継ぎます。検索欄を空にし、列またはドックグループの見出しにあるリセットアイコンを押すと、その階層をリセットできます。全階層をリセットするには、デスクトップでは「位置」列の見出し右側にある更新アイコン(「すべての並び順をリセット」)、モバイルでは下部の「すべての並び順をリセット」ボタンを押します。確認すると保存され、キャンセルすると変更を破棄します。並び順のリセットでは表示設定とドック項目の配置場所は維持され、リセットした階層は今後の初期順序の変更にも従います。"}]+ },+ {+ "ID": "20261020212341-qz5a74f",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20261020212341-qz5a74f",+ "updated": "20261020212341"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "文書末尾のバックリンク"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20261020212341-41di2j5",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261020212341-41di2j5",+ "updated": "20261020212341"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "デスクトップとモバイルの両方で "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "エディタ"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "双方向リンク"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "文書の下部にバックリンクパネルを表示"+ },+ {+ "Type": "NodeText",+ "Data": " を有効にすると、文書末尾にバックリンクとメンションを表示できます。パネルに近づくと読み込まれます。本文の末尾が読み込まれた後に表示され、結果がない場合は非表示になります。"+ }+ ]}]}diff --git a/app/src/assets/scss/main/_mobile.scss b/app/src/assets/scss/main/_mobile.scssindex 0037968d39..a54406276d 100644--- a/app/src/assets/scss/main/_mobile.scss+++ b/app/src/assets/scss/main/_mobile.scss@@ -1979,10 +1979,6 @@ body.mobile-topbar--merged {> .backlinkList,> .backlinkMList {- min-height: 0;- overflow: auto;- overscroll-behavior: contain;-> .b3-list > .backlinkList__item > .b3-list-item {margin-left: 0;margin-right: 0;@@ -1990,6 +1986,15 @@ body.mobile-topbar--merged {}}+ &:not(.sy__backlink--bottom) {+ > .backlinkList,+ > .backlinkMList {+ min-height: 0;+ overflow: auto;+ overscroll-behavior: contain;+ }+ }+.protyle-breadcrumb__bar {min-height: 32px;}diff --git a/app/src/config/tabs/editorBottomBacklink.test.ts b/app/src/config/tabs/editorBottomBacklink.test.tsnew file mode 100644index 0000000000..61e894afa9--- /dev/null+++ b/app/src/config/tabs/editorBottomBacklink.test.ts@@ -0,0 +1,61 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {createSourceFile, forEachChild, isObjectLiteralExpression, ScriptTarget, transpileModule} from "typescript";+import {shouldResetBottomBacklinkPanel} from "./editorRuntimeState";++const {parse} = require("ifdef-loader/preprocessor");+const sourceFor = (file: string, mobile: boolean) => createSourceFile(file,+ parse(readFileSync(`src/config/tabs/${file}`, "utf8"), {BROWSER: true, MOBILE: mobile}, false, true),+ ScriptTarget.ES2021, true);+const compile = (source: string) => transpileModule(source, {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;++for (const mobile of [false, true]) {+ test(`bottom backlink switch uses the existing editor setting (mobile=${mobile})`, () => {+ const source = sourceFor("editorTab.ts", mobile);+ const registration = source.statements.find(node => node.getText(source).startsWith("const registerEditorBidirectionalGroup ="));+ assert.ok(registration);+ const switches: string[] = [];+ const group = new Proxy({}, {get: (_, kind: string) => (id: string) => {+ if (kind === "switch") switches.push(id);+ }});+ runInNewContext(compile(registration.getText(source)) + "\nregisterEditorBidirectionalGroup(tab);", {+ tab: {group: () => group}, isMobile: () => mobile,+ window: {siyuan: {languages: new Proxy({}, {get: (_, key) => String(key)})}},+ });+ assert.equal(switches.filter(id => id === "editor.backlinkShowBottom").length, 1);+ });++ test(`bottom backlink settings update the active platform and await mobile saves (mobile=${mobile})`, async () => {+ const source = sourceFor("editorRuntime.ts", mobile);+ let applySource: string;+ const visit = (node: import("typescript").Node) => {+ if (isObjectLiteralExpression(node) && node.properties.some(property =>+ property.getText(source) === 'name: "backlink-panel"')) {+ const property = node.properties.find(item => item.name?.getText(source) === "apply");+ applySource = property.getText(source).slice("apply:".length);+ }+ forEachChild(node, visit);+ };+ visit(source);+ assert.ok(applySource);+ let saved: () => void;+ const pending = new Promise<void>(resolve => { saved = resolve; });+ const calls: string[] = [];+ const apply = runInNewContext(compile(`const apply = ${applySource};`) + "\napply;", {+ shouldResetBottomBacklinkPanel,+ updateMobileBottomBacklinkPanel: (_protyle: unknown, reset: boolean) => {+ calls.push(`mobile:${reset}`);+ return pending;+ },+ getAllModels: () => ({editor: [{updateBacklinkPanel: (reset: boolean) => calls.push(`desktop:${reset}`)}]}),+ });+ const current = {backlinkExpandCount: 0, backmentionExpandCount: 0};+ const result = apply(current, {...current, backlinkExpandCount: 1});+ assert.deepEqual(calls, [mobile ? "mobile:true" : "desktop:true"]);+ if (mobile) assert.equal(result, pending);+ saved();+ await result;+ });+}diff --git a/app/src/config/tabs/editorRuntime.ts b/app/src/config/tabs/editorRuntime.tsindex e5de167eee..3b66affab3 100644--- a/app/src/config/tabs/editorRuntime.ts+++ b/app/src/config/tabs/editorRuntime.ts@@ -11,6 +11,7 @@ import {lineNumberRender} from "../../protyle/render/highlightRender";import {updatePageScrollButtons} from "../../protyle/scroll/pageButtons";/// #if MOBILEimport {setTitleAutoDirection} from "../../protyle/render/autoDirection";+import {updateMobileBottomBacklinkPanel} from "../../mobile/util/bottomBacklink";/// #endifconst runtime = createSectionRuntime<Config.IEditor>({@@ -25,7 +26,11 @@ const runtime = createSectionRuntime<Config.IEditor>({name: "backlink-panel",changed: () => true,apply: (old, next) => {+ /// #if MOBILE+ return updateMobileBottomBacklinkPanel(undefined, shouldResetBottomBacklinkPanel(old, next));+ /// #elsegetAllModels().editor.forEach(item => item.updateBacklinkPanel(shouldResetBottomBacklinkPanel(old, next)));+ /// #endif},}, {name: "database-row-layout",diff --git a/app/src/config/tabs/editorTab.ts b/app/src/config/tabs/editorTab.tsindex 21e7f6c747..07fd99cef3 100644--- a/app/src/config/tabs/editorTab.ts+++ b/app/src/config/tabs/editorTab.ts@@ -353,12 +353,10 @@ const registerEditorBidirectionalGroup = (tab: SettingTabBuilder) => {title: window.siyuan.languages.backlinkHideReference,desc: window.siyuan.languages.backlinkHideReferenceTip,});- if (!isMobile()) {- group.switch("editor.backlinkShowBottom", {- title: window.siyuan.languages.backlinkShowBottom,- desc: window.siyuan.languages.backlinkShowBottomTip,- });- }+ group.switch("editor.backlinkShowBottom", {+ title: window.siyuan.languages.backlinkShowBottom,+ desc: window.siyuan.languages.backlinkShowBottomTip,+ });group.number("editor.backlinkExpandCount", {title: window.siyuan.languages.backlinkExpand,desc: window.siyuan.languages.backlinkExpandTip,diff --git a/app/src/editor/index.ts b/app/src/editor/index.tsindex 6e5d000e7e..1ab3bd79f3 100644--- a/app/src/editor/index.ts+++ b/app/src/editor/index.ts@@ -1,26 +1,25 @@import {Tab} from "../layout/Tab";import {Protyle} from "../protyle";import {Model} from "../layout/Model";-import {setPadding} from "../protyle/ui/initUI";/// #if !BROWSERimport {setModelsHash} from "../window/setHeader";/// #endifimport {countBlockWord} from "../layout/status";import type {App} from "../index";import {fetchPost} from "../util/fetch";-import {Backlink} from "../layout/dock/Backlink";+import {BottomBacklinkPanel} from "../layout/dock/BottomBacklinkPanel";import type {IDatabaseRowOpenData} from "../protyle/render/av/openDatabaseRow";export class Editor extends Model {public element: HTMLElement;public editor: Protyle;public headElement: HTMLElement;- public backlink?: Backlink;public databaseRow?: IDatabaseRowOpenData;- private backlinkElement?: HTMLElement;- private backlinkIntersectionObserver?: IntersectionObserver;- private backlinkMutationObserver?: MutationObserver;- private backlinkEmpty = false;+ private bottomBacklinkPanel?: BottomBacklinkPanel;++ public get backlink() {+ return this.bottomBacklinkPanel?.backlink;+ }constructor(options: {app: App,@@ -91,87 +90,16 @@ export class Editor extends Model {}public updateBacklinkPanel(reset = false) {- if (reset) {- this.destroyBacklinkPanel();- }- if (!window.siyuan.config.editor.backlinkShowBottom) {- this.destroyBacklinkPanel();- return;- }- if (this.backlinkElement) {- this.updateBacklinkVisibility();- return;- }-- const backlinkElement = document.createElement("div");- backlinkElement.className = "fn__none sy__backlink--bottom sy__backlink--pending";- this.backlinkElement = backlinkElement;- this.editor.protyle.wysiwyg.element.after(backlinkElement);- setPadding(this.editor.protyle);-- this.backlinkIntersectionObserver = new IntersectionObserver((entries) => {- if (this.backlinkElement !== backlinkElement || !entries[0].isIntersecting ||- backlinkElement.classList.contains("fn__none")) {- return;- }- if (!this.backlink) {- this.backlink = new Backlink({- app: this.app,- blockId: this.getBacklinkBlockId(),- rootId: this.editor.protyle.block.rootID,- notebookId: this.editor.protyle.notebookId,- type: "bottom",- element: backlinkElement,- ownerProtyle: this.editor.protyle,- emptyChange: (empty) => {- if (this.backlinkElement !== backlinkElement) {- return;- }- const pending = backlinkElement.classList.contains("sy__backlink--pending");- if (!pending && this.backlinkEmpty === empty) {- return;- }- const contentElement = this.editor.protyle.contentElement;- contentElement.classList.add("protyle-content--backlink-reveal");- backlinkElement.classList.remove("sy__backlink--pending");- this.backlinkEmpty = empty;- this.updateBacklinkVisibility(pending);- contentElement.getBoundingClientRect();- requestAnimationFrame(() => {- contentElement.classList.remove("protyle-content--backlink-reveal");- });- },- });- } else {- this.backlink.refreshDirty();- }- }, {- root: this.editor.protyle.contentElement,- rootMargin: "640px 0px",- });- this.backlinkIntersectionObserver.observe(backlinkElement);-- this.backlinkMutationObserver = new MutationObserver(() => {- this.updateBacklinkVisibility();- });- this.backlinkMutationObserver.observe(this.editor.protyle.wysiwyg.element, {- attributes: true,- attributeFilter: ["data-bottom-eof"],- });- this.updateBacklinkVisibility();+ this.bottomBacklinkPanel ??= new BottomBacklinkPanel(this.editor.protyle);+ this.bottomBacklinkPanel.update(reset);}public refreshBottomBacklinkPanel() {- if (!this.backlink) {- return;- }- const blockId = this.getBacklinkBlockId();- const rootId = this.editor.protyle.block.rootID;- this.backlink.switchBlock(blockId, rootId, this.editor.protyle.notebookId);+ this.bottomBacklinkPanel?.refresh();}public destroy() {- this.destroyBacklinkPanel();+ this.bottomBacklinkPanel?.destroy();this.editor.destroy();}@@ -184,37 +112,4 @@ export class Editor extends Model {}return this.editor.protyle;}-- private getBacklinkBlockId() {- const protyle = this.editor.protyle;- return protyle.block.showAll ? protyle.block.id : (protyle.block.parentID || protyle.block.rootID);- }-- private updateBacklinkVisibility(forcePadding = false) {- if (!this.backlinkElement) {- return;- }- const hidden = this.backlinkEmpty || (!this.editor.protyle.block.showAll && this.editor.protyle.block.scroll &&- !this.editor.protyle.wysiwyg.element.hasAttribute("data-bottom-eof"));- if (this.backlinkElement.classList.contains("fn__none") !== hidden || forcePadding) {- this.backlinkElement.classList.toggle("fn__none", hidden);- setPadding(this.editor.protyle);- }- }-- private destroyBacklinkPanel() {- const hasBacklinkElement = !!this.backlinkElement;- this.backlinkIntersectionObserver?.disconnect();- this.backlinkMutationObserver?.disconnect();- this.backlink?.destroy();- this.backlinkElement?.remove();- this.backlinkIntersectionObserver = undefined;- this.backlinkMutationObserver = undefined;- this.backlink = undefined;- this.backlinkElement = undefined;- this.backlinkEmpty = false;- if (hasBacklinkElement) {- setPadding(this.editor.protyle);- }- }}diff --git a/app/src/layout/dock/BottomBacklinkPanel.test.ts b/app/src/layout/dock/BottomBacklinkPanel.test.tsnew file mode 100644index 0000000000..924a62aaf5--- /dev/null+++ b/app/src/layout/dock/BottomBacklinkPanel.test.ts@@ -0,0 +1,147 @@+import * as assert from "node:assert/strict";+import {execFile} from "node:child_process";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import * as path from "node:path";+import {test} from "node:test";+import {promisify} from "node:util";+import {ScriptTarget, transpileModule} from "typescript";+import {compile} from "sass";++const browserCases = async (source: string, css: string) => {+ const check: typeof assert = require("node:assert/strict");+ const wait = () => new Promise(resolve => setTimeout(resolve, 100));+ const created: Array<{options: any, destroyed: boolean, refreshes: number}> = [];+ let registrations = 0;+ let removals = 0;+ class Backlink {+ private record: typeof created[number];+ constructor(options: any) {+ this.record = {options, destroyed: false, refreshes: 0};+ created.push(this.record);+ options.element.classList.add("sy__backlink");+ options.element.innerHTML = '<div class="backlinkList">Backlinks</div>';+ queueMicrotask(() => options.emptyChange(false));+ }+ refreshDirty() { this.record.refreshes++; }+ switchBlock(blockId: string, rootId: string, notebookId: string) {+ Object.assign(this.record.options, {blockId, rootId, notebookId});+ }+ destroy() { this.record.destroyed = true; }+ }+ const {BottomBacklinkPanel, getBottomBacklinkBlockId} = new Function("Backlink", "setPadding", source ++ "\nreturn {BottomBacklinkPanel, getBottomBacklinkBlockId};")(Backlink, () => {});+ window.siyuan = {config: {editor: {backlinkShowBottom: true}}} as unknown as typeof window.siyuan;+ const style = document.createElement("style");+ style.textContent = css;+ document.head.append(style);+ const owner = document.createElement("div");+ owner.className = "protyle";+ owner.innerHTML = '<div class="protyle-content"><div class="protyle-wysiwyg"></div></div>';+ document.body.append(owner);+ const content = owner.firstElementChild as HTMLElement;+ content.style.cssText = "height:200px;width:360px;overflow-y:auto";+ const wysiwyg = content.firstElementChild as HTMLElement;+ wysiwyg.style.cssText = "height:1800px;flex:none";+ const protyle = {app: {}, element: owner, contentElement: content, wysiwyg: {element: wysiwyg},+ notebookId: "encrypted-box", block: {id: "doc", rootID: "doc", parentID: "", showAll: false, scroll: true}};+ const panel = new BottomBacklinkPanel(protyle, () => {+ registrations++;+ return () => {removals++;};+ });+ panel.update();+ const element = content.querySelector<HTMLElement>(".sy__backlink--bottom");+ check.ok(element);+ check.equal(element.classList.contains("fn__none"), true, "partial documents hide bottom backlinks");+ await wait();+ check.equal(created.length, 0);+ wysiwyg.setAttribute("data-bottom-eof", "true");+ await wait();+ check.equal(element.classList.contains("fn__none"), false);+ check.equal(created.length, 0, "backlinks outside the prefetch margin remain unloaded");+ content.scrollTop = content.scrollHeight;+ await wait();+ check.equal(created.length, 1);+ check.equal(created[0].options.blockId, "doc");+ check.equal(created[0].options.notebookId, "encrypted-box");+ check.equal(registrations, 1);+ check.equal(element.classList.contains("sy__backlink--pending"), false);+ check.equal(getComputedStyle(element.querySelector(".backlinkList")).overflowY, "visible",+ "mobile bottom backlinks share document scrolling");+ const dock = document.createElement("div");+ dock.className = "sy__backlink";+ dock.innerHTML = '<div class="backlinkList"></div>';+ document.body.append(dock);+ check.equal(getComputedStyle(dock.firstElementChild).overflowY, "auto", "mobile dock retains independent scrolling");+ panel.update();+ check.equal(content.querySelectorAll(".sy__backlink--bottom").length, 1);+ check.equal(created.length, 1);+ created[0].options.emptyChange(true);+ check.equal(element.classList.contains("fn__none"), true);+ created[0].options.emptyChange(false);+ check.equal(element.classList.contains("fn__none"), false);+ protyle.block.showAll = true;+ protyle.block.id = "zoomed";+ check.equal(getBottomBacklinkBlockId(protyle), "zoomed");+ panel.refresh();+ check.equal(created[0].options.blockId, "zoomed");+ const staleCallback = created[0].options.emptyChange;+ window.siyuan.config.editor.backlinkShowBottom = false;+ panel.update();+ check.equal(created[0].destroyed, true);+ check.equal(removals, 1);+ check.equal(content.querySelector(".sy__backlink--bottom"), null);+ window.siyuan.config.editor.backlinkShowBottom = true;+ panel.update();+ staleCallback(true);+ check.equal(content.querySelector(".sy__backlink--bottom").classList.contains("fn__none"), false,+ "a destroyed panel cannot hide its replacement");+ panel.destroy();+ await wait();+ check.equal(content.querySelector(".sy__backlink--bottom"), null);+ owner.remove();+ dock.remove();+ style.remove();+ return "Bottom backlink browser cases passed";+};++test("bottom backlinks preserve lazy loading, visibility, cleanup and mobile scrolling", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 30000,+}, async () => {+ const source = readFileSync(path.join(__dirname, "BottomBacklinkPanel.ts"), "utf8");+ const compiled = transpileModule(source.slice(source.indexOf("export const getBottomBacklinkBlockId"))+ .replace(/export /g, ""), {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;+ const css = compile(path.join(__dirname, "../../assets/scss/mobile.scss"), {logger: {warn: () => {}}}).css;+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-bottom-backlink-test-"));+ const script = path.join(temporary, "run.cjs");+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.commandLine.appendSwitch("disable-gpu");+app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});+ try {+ await win.loadURL("data:text/html,<html><body></body></html>");+ console.log(await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" ++ browserCases.toString() + ")(" + JSON.stringify(compiled) + "," + JSON.stringify(css) + ")")}));+ win.destroy();+ app.exit(0);+ } catch (error) {+ console.error(error);+ win.destroy();+ app.exit(1);+ }+});`, "utf8");+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],+ {env, timeout: 25000, windowsHide: true});+ assert.match(result.stdout, /Bottom backlink browser cases passed/);+ } finally {+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&+ path.basename(temporary).startsWith("siyuan-bottom-backlink-test-")) {+ rmSync(temporary, {recursive: true, force: true});+ }+ }+});diff --git a/app/src/layout/dock/BottomBacklinkPanel.ts b/app/src/layout/dock/BottomBacklinkPanel.tsnew file mode 100644index 0000000000..90ef88b622--- /dev/null+++ b/app/src/layout/dock/BottomBacklinkPanel.ts@@ -0,0 +1,133 @@+import {Backlink} from "./Backlink";+import {setPadding} from "../../protyle/ui/initUI";++export const getBottomBacklinkBlockId = (protyle: IProtyle) => {+ return protyle.block.showAll ? protyle.block.id : (protyle.block.parentID || protyle.block.rootID);+};++export class BottomBacklinkPanel {+ public backlink?: Backlink;+ private backlinkElement?: HTMLElement;+ private backlinkIntersectionObserver?: IntersectionObserver;+ private backlinkMutationObserver?: MutationObserver;+ private backlinkEmpty = false;+ private unregisterPanel?: () => void;++ constructor(private protyle: IProtyle, private registerPanel?: (panel: Backlink) => () => void) {+ }++ public update(reset = false) {+ if (reset) {+ this.destroy();+ }+ if (!window.siyuan.config.editor.backlinkShowBottom) {+ this.destroy();+ return;+ }+ if (this.backlinkElement) {+ this.updateBacklinkVisibility();+ return;+ }++ const backlinkElement = document.createElement("div");+ backlinkElement.className = "fn__none sy__backlink--bottom sy__backlink--pending";+ this.backlinkElement = backlinkElement;+ this.protyle.wysiwyg.element.after(backlinkElement);+ setPadding(this.protyle);++ this.backlinkIntersectionObserver = new IntersectionObserver((entries) => {+ if (this.backlinkElement !== backlinkElement || !entries[0].isIntersecting ||+ backlinkElement.classList.contains("fn__none")) {+ return;+ }+ if (!this.backlink) {+ this.backlink = new Backlink({+ app: this.protyle.app,+ blockId: this.getBacklinkBlockId(),+ rootId: this.protyle.block.rootID,+ notebookId: this.protyle.notebookId,+ type: "bottom",+ element: backlinkElement,+ ownerProtyle: this.protyle,+ emptyChange: (empty) => {+ if (this.backlinkElement !== backlinkElement) {+ return;+ }+ const pending = backlinkElement.classList.contains("sy__backlink--pending");+ if (!pending && this.backlinkEmpty === empty) {+ return;+ }+ const contentElement = this.protyle.contentElement;+ contentElement.classList.add("protyle-content--backlink-reveal");+ backlinkElement.classList.remove("sy__backlink--pending");+ this.backlinkEmpty = empty;+ this.updateBacklinkVisibility(pending);+ contentElement.getBoundingClientRect();+ requestAnimationFrame(() => {+ contentElement.classList.remove("protyle-content--backlink-reveal");+ });+ },+ });+ this.unregisterPanel = this.registerPanel?.(this.backlink);+ } else {+ this.backlink.refreshDirty();+ }+ }, {+ root: this.protyle.contentElement,+ rootMargin: "640px 0px",+ });+ this.backlinkIntersectionObserver.observe(backlinkElement);++ this.backlinkMutationObserver = new MutationObserver(() => {+ this.updateBacklinkVisibility();+ });+ this.backlinkMutationObserver.observe(this.protyle.wysiwyg.element, {+ attributes: true,+ attributeFilter: ["data-bottom-eof"],+ });+ this.updateBacklinkVisibility();+ }++ public refresh() {+ if (!this.backlink) {+ return;+ }+ const blockId = this.getBacklinkBlockId();+ const rootId = this.protyle.block.rootID;+ this.backlink.switchBlock(blockId, rootId, this.protyle.notebookId);+ }++ private getBacklinkBlockId() {+ return getBottomBacklinkBlockId(this.protyle);+ }++ private updateBacklinkVisibility(forcePadding = false) {+ if (!this.backlinkElement) {+ return;+ }+ const hidden = this.backlinkEmpty || (!this.protyle.block.showAll && this.protyle.block.scroll &&+ !this.protyle.wysiwyg.element.hasAttribute("data-bottom-eof"));+ if (this.backlinkElement.classList.contains("fn__none") !== hidden || forcePadding) {+ this.backlinkElement.classList.toggle("fn__none", hidden);+ setPadding(this.protyle);+ }+ }++ public destroy() {+ const hasBacklinkElement = !!this.backlinkElement;+ this.backlinkIntersectionObserver?.disconnect();+ this.backlinkMutationObserver?.disconnect();+ this.unregisterPanel?.();+ this.unregisterPanel = undefined;+ this.backlink?.destroy();+ this.backlinkElement?.remove();+ this.backlinkIntersectionObserver = undefined;+ this.backlinkMutationObserver = undefined;+ this.backlink = undefined;+ this.backlinkElement = undefined;+ this.backlinkEmpty = false;+ if (hasBacklinkElement) {+ setPadding(this.protyle);+ }+ }+}diff --git a/app/src/mobile/editor.scroll.test.ts b/app/src/mobile/editor.scroll.test.tsindex 9046876f0a..12347588eb 100644--- a/app/src/mobile/editor.scroll.test.ts+++ b/app/src/mobile/editor.scroll.test.ts@@ -54,6 +54,7 @@ const setup = (legacy?: IScrollAttr, encrypted = false) => {const presentation: string[] = [];const attributes: Array<(ready: boolean) => void> = [];const toolbar = {value: "Document"};+ const bottomBacklink = {close: (): Promise<void> | undefined => undefined, updates: 0};const window: any = {siyuan: {storage: {positions: {root: clone(legacy)}},config: {editor: {dynamicLoadBlocks: 128, databaseAttrShow: true}, fileTree: {}}, mobile: {},@@ -138,6 +139,8 @@ const setup = (legacy?: IScrollAttr, encrypted = false) => {"./util/mobileTopBar": {restoreMobileTopBarLayout: noop},"./util/MobileEditorDialog": {closeMobileEditorSheets: noop},"./util/openReference": {invalidateMobileReferenceOpen: noop},+ "./util/bottomBacklink": {closeMobileBottomBacklinkPanel: () => bottomBacklink.close(),+ updateMobileBottomBacklinkPanel: () => { bottomBacklink.updates++; return Promise.resolve(); }},});const load = (scrollAttr?: IScrollAttr) => new Promise<any>((resolve, reject) => {loader.loadMobileFileById({}, "root", [constants.CB_GET_SCROLL], undefined, notebookID, resolve,@@ -151,10 +154,24 @@ const setup = (legacy?: IScrollAttr, encrypted = false) => {resolve(false);}, false, true);});- return {load, switchRow, requests, rendered, constructed, window, presentation, attributes,+ return {load, switchRow, requests, rendered, constructed, window, presentation, attributes, bottomBacklink,get docRequest() { return requests.filter(item => item.url === "/api/filetree/getDoc").at(-1)?.data; }};};+test("mobile document loading waits for bottom backlink input before reusing the editor", async () => {+ const state = setup();+ let saved: () => void;+ const pending = new Promise<void>(resolve => { saved = resolve; });+ state.bottomBacklink.close = () => pending;+ const loading = state.load();+ assert.equal(state.requests.length, 0);+ state.bottomBacklink.close = () => undefined;+ saved();+ await loading;+ assert.ok(state.requests.length > 0);+ assert.equal(state.bottomBacklink.updates, 1);+});+test("cold mobile loading restores the tab's top instead of the document's old bottom", async () => {const state = setup(position(8000, {startId: "old-first", endId: "old-last"}));const scroll = position(0);diff --git a/app/src/mobile/editor.ts b/app/src/mobile/editor.tsindex b611eeb0f0..460d737e2a 100644--- a/app/src/mobile/editor.ts+++ b/app/src/mobile/editor.ts@@ -28,6 +28,7 @@ import {invalidateMobileReferenceOpen} from "./util/openReference";import {closeAVCellEditor} from "../protyle/render/av/cellEditor";import {clearDatabaseRowNavigation} from "../protyle/render/av/databaseRowNavigation";import {prepareDatabaseAttributePanel} from "../protyle/render/av/attributePanel";+import {closeMobileBottomBacklinkPanel, updateMobileBottomBacklinkPanel} from "./util/bottomBacklink";export const getCurrentEditor = () => {return getActiveMobileSecondaryEditor() || window.siyuan.mobile.popEditor || window.siyuan.mobile.editor;@@ -75,7 +76,7 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[onFailure?: (invalid?: boolean, editorUnchanged?: boolean) => void, keepPanels = false,waitForDatabaseAttributes = false) => {invalidateMobileReferenceOpen();- const closing = closeMobileEditorSheets();+ const closing = closeMobileEditorSheets() || closeMobileBottomBacklinkPanel();if (closing) {void closing.then(() => {if (isValid() && !signal?.aborted) {@@ -99,6 +100,7 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[completed = true;clearDatabaseRowNavigation(protyle.element);setEditor();+ void updateMobileBottomBacklinkPanel(protyle).catch(error => console.error(error));bindMobileBarsScroll(protyle.contentElement, () => {// 面包屑位移后同步数据库吸顶位置,避免数据库使用上一帧的面包屑位置protyle.wysiwyg.element.querySelectorAll(".av[data-render='true']").forEach((item: HTMLElement) => {@@ -126,6 +128,9 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[if (titleHidden && isValid() && window.siyuan.mobile.editor?.protyle.wysiwyg.element.childElementCount > 0) {setEditor();}+ if (isValid()) {+ void updateMobileBottomBacklinkPanel().catch(error => console.error(error));+ }onFailure?.(invalid, !titleHidden);};if (!isValid()) {diff --git a/app/src/mobile/util/bottomBacklink.test.ts b/app/src/mobile/util/bottomBacklink.test.tsnew file mode 100644index 0000000000..398935e66d--- /dev/null+++ b/app/src/mobile/util/bottomBacklink.test.ts@@ -0,0 +1,147 @@+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 setup = () => {+ const panels: Panel[] = [];+ const pending: Array<{resolve: () => void, reject: (error: Error) => void}> = [];+ const registered = new Set<Panel>();+ const makeProtyle = (id: string, notebookId = "box") => ({+ block: {id, rootID: id, showAll: false}, notebookId,+ element: {classList: {contains: () => false}},+ contentElement: {querySelector: () => ({+ setAttribute: () => {}, removeAttribute: () => {},+ })},+ });+ const window = {siyuan: {config: {editor: {backlinkShowBottom: true}},+ mobile: {editor: {protyle: makeProtyle("first")}}}};+ class Panel {+ backlink: {blockId: string, rootId: string, notebookId: string, editors: object[]};+ destroyed = false;+ private unregister: () => void;+ constructor(private protyle: ReturnType<typeof makeProtyle>, private register: (panel: Panel) => () => void) {+ panels.push(this);+ }+ update() {+ if (!this.backlink) {+ this.backlink = {blockId: this.protyle.block.id, rootId: this.protyle.block.rootID,+ notebookId: this.protyle.notebookId, editors: [{}]};+ this.unregister = this.register(this);+ }+ }+ destroy() {+ this.destroyed = true;+ this.unregister?.();+ }+ }+ const api: typeof import("./bottomBacklink") = {} as never;+ const code = transpileModule(readFileSync(join(__dirname, "bottomBacklink.ts"), "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;+ const modules = {+ "../../layout/dock/BottomBacklinkPanel": {BottomBacklinkPanel: Panel,+ getBottomBacklinkBlockId: (protyle: ReturnType<typeof makeProtyle>) => protyle.block.id},+ "./backlinkPanels": {registerMobileBacklinkPanel: (panel: Panel) => {+ registered.add(panel);+ return () => registered.delete(panel);+ }},+ "./secondaryEditors": {flushMobileSecondaryEditor: () => new Promise<void>((resolve, reject) => {+ pending.push({resolve, reject});+ })},+ };+ runInNewContext(code, {window, exports: api, require: (name: keyof typeof modules) => modules[name]});+ return {api, window, panels, pending, registered, makeProtyle};+};++test("mobile bottom backlinks save inputs before switching documents and retain notebook scope", async () => {+ const state = setup();+ await state.api.updateMobileBottomBacklinkPanel();+ const closing = state.api.closeMobileBottomBacklinkPanel();+ assert.equal(state.panels[0].destroyed, false);+ assert.equal(state.registered.size, 1);+ state.pending[0].resolve();+ await closing;+ assert.equal(state.panels[0].destroyed, true);+ assert.equal(state.registered.size, 0);+ state.window.siyuan.mobile.editor.protyle = state.makeProtyle("second", "encrypted-box");+ await state.api.updateMobileBottomBacklinkPanel();+ assert.equal(state.panels[1].backlink.blockId, "second");+ assert.equal(state.panels[1].backlink.notebookId, "encrypted-box");+});++test("mobile bottom backlinks retain unsaved input on failure and allow retry", async () => {+ const state = setup();+ await state.api.updateMobileBottomBacklinkPanel();+ const closing = state.api.closeMobileBottomBacklinkPanel();+ state.pending[0].reject(new Error("save failed"));+ await assert.rejects(closing, /save failed/);+ assert.equal(state.panels[0].destroyed, false);+ assert.equal(state.registered.size, 1);+ const retry = state.api.closeMobileBottomBacklinkPanel();+ state.pending[1].resolve();+ await retry;+ assert.equal(state.panels[0].destroyed, true);+});++test("disabling and resetting mobile bottom backlinks flushes editors before removing them", async () => {+ for (const reset of [false, true]) {+ const state = setup();+ await state.api.updateMobileBottomBacklinkPanel();+ state.window.siyuan.config.editor.backlinkShowBottom = reset;+ const updating = state.api.updateMobileBottomBacklinkPanel(undefined, reset);+ assert.equal(state.panels[0].destroyed, false);+ state.pending[0].resolve();+ await updating;+ assert.equal(state.panels[0].destroyed, true);+ assert.equal(state.registered.size, reset ? 1 : 0);+ if (!reset) {+ state.window.siyuan.config.editor.backlinkShowBottom = true;+ await state.api.updateMobileBottomBacklinkPanel();+ assert.equal(state.registered.size, 1);+ }+ }+});++test("zooming and switching notebooks replaces the mobile panel after saving", async () => {+ for (const key of ["block", "notebook"]) {+ const state = setup();+ await state.api.updateMobileBottomBacklinkPanel();+ const protyle = state.window.siyuan.mobile.editor.protyle;+ if (key === "block") protyle.block.id = "zoomed";+ else protyle.notebookId = "encrypted-box";+ const updating = state.api.updateMobileBottomBacklinkPanel();+ state.pending[0].resolve();+ await updating;+ assert.equal(state.panels[0].destroyed, true);+ assert.equal(state.panels[1].backlink.blockId, protyle.block.id);+ assert.equal(state.panels[1].backlink.notebookId, protyle.notebookId);+ }+});++test("navigation cancels a pending reset without recreating an old document's panel", async () => {+ const state = setup();+ await state.api.updateMobileBottomBacklinkPanel();+ const resetting = state.api.updateMobileBottomBacklinkPanel(undefined, true);+ const closing = state.api.closeMobileBottomBacklinkPanel();+ assert.equal(state.pending.length, 1);+ state.pending[0].resolve();+ await Promise.all([resetting, closing]);+ assert.equal(state.panels.length, 1);+ assert.equal(state.registered.size, 0);+});++test("destroying the owner releases its panel and stale close completion preserves the next panel", async () => {+ const state = setup();+ await state.api.updateMobileBottomBacklinkPanel();+ const closing = state.api.closeMobileBottomBacklinkPanel();+ state.api.destroyMobileBottomBacklinkPanel(state.window.siyuan.mobile.editor.protyle as unknown as IProtyle);+ state.window.siyuan.mobile.editor.protyle = state.makeProtyle("next");+ await state.api.updateMobileBottomBacklinkPanel();+ state.pending[0].resolve();+ await closing;+ assert.equal(state.registered.size, 1);+ assert.equal(state.panels[1].destroyed, false);+});diff --git a/app/src/mobile/util/bottomBacklink.ts b/app/src/mobile/util/bottomBacklink.tsnew file mode 100644index 0000000000..ba8bb2f0fa--- /dev/null+++ b/app/src/mobile/util/bottomBacklink.ts@@ -0,0 +1,64 @@+import {BottomBacklinkPanel, getBottomBacklinkBlockId} from "../../layout/dock/BottomBacklinkPanel";+import {registerMobileBacklinkPanel} from "./backlinkPanels";+import {flushMobileSecondaryEditor} from "./secondaryEditors";++type MobileBottomBacklink = {+ protyle: IProtyle;+ panel: BottomBacklinkPanel;+ closing?: Promise<void>;+};++let current: MobileBottomBacklink;+let generation = 0;++const closePanel = (record: MobileBottomBacklink) => {+ if (!record.closing) {+ const element = record.protyle.contentElement.querySelector(".sy__backlink--bottom");+ element?.setAttribute("inert", "");+ record.closing = Promise.all((record.panel.backlink?.editors || []).map(flushMobileSecondaryEditor)).then(() => {+ record.panel.destroy();+ if (current === record) {+ current = undefined;+ }+ }).catch(error => {+ element?.removeAttribute("inert");+ record.closing = undefined;+ throw error;+ });+ }+ return record.closing;+};++// 切换正文前提交反链编辑器的防抖输入,失败时保留面板和输入以便重试。+export const closeMobileBottomBacklinkPanel = () => {+ generation++;+ return current ? closePanel(current) : undefined;+};++export const updateMobileBottomBacklinkPanel = async (protyle = window.siyuan.mobile.editor?.protyle, reset = false) => {+ const version = ++generation;+ if (!protyle || protyle !== window.siyuan.mobile.editor?.protyle || protyle.element.classList.contains("fn__none")) {+ return;+ }+ const enabled = window.siyuan.config.editor.backlinkShowBottom;+ const backlink = current?.panel.backlink;+ if (current && (current.closing || reset || !enabled || current.protyle !== protyle || backlink &&+ (backlink.blockId !== getBottomBacklinkBlockId(protyle) || backlink.rootId !== protyle.block.rootID ||+ backlink.notebookId !== (protyle.notebookId || "")))) {+ await closePanel(current);+ }+ if (version !== generation || !enabled || protyle !== window.siyuan.mobile.editor?.protyle) {+ return;+ }+ current ??= {protyle, panel: new BottomBacklinkPanel(protyle, registerMobileBacklinkPanel)};+ current.panel.update();+};++export const destroyMobileBottomBacklinkPanel = (protyle: IProtyle) => {+ if (current?.protyle === protyle) {+ generation++;+ const record = current;+ current = undefined;+ record.panel.destroy();+ }+};diff --git a/app/src/mobile/util/saveLayout.integration.test.ts b/app/src/mobile/util/saveLayout.integration.test.tsindex af06d19eae..d1f0df37b8 100644--- a/app/src/mobile/util/saveLayout.integration.test.ts+++ b/app/src/mobile/util/saveLayout.integration.test.ts@@ -149,6 +149,7 @@ test("mobile loader distinguishes early failures from a partially changed editorwindow: {siyuan: {mobile: {editor: {protyle: {wysiwyg: {element: {childElementCount: 1}}}}}}},setEditor: () => { shown++; },onFailure: (...args: unknown[]) => failures.push(args),+ updateMobileBottomBacklinkPanel: () => Promise.resolve(),});assert.deepEqual(failures, [[true, !titleHidden]]);assert.equal(shown, titleHidden ? 1 : 0);diff --git a/app/src/mobile/util/setEmpty.ts b/app/src/mobile/util/setEmpty.tsindex 20df091587..a424ab9f0d 100644--- a/app/src/mobile/util/setEmpty.ts+++ b/app/src/mobile/util/setEmpty.ts@@ -9,6 +9,7 @@ import {clearMobileBarsScroll} from "./mobileBars";import {updateMobileTopBarLayout} from "./mobileTopBar";import {invalidateTrackedRanges} from "../../protyle/util/trackedRange";import {closeAVCellEditor} from "../../protyle/render/av/cellEditor";+import {closeMobileBottomBacklinkPanel} from "./bottomBacklink";export const finishMobileStartup = () => {const loadingElement = document.getElementById("loading");@@ -19,6 +20,7 @@ export const finishMobileStartup = () => {};export const setEmpty = (app: App) => {+ void closeMobileBottomBacklinkPanel()?.catch(error => console.error(error));closeAVCellEditor();if (window.siyuan.mobile.editor?.protyle) {invalidateTrackedRanges(window.siyuan.mobile.editor.protyle);diff --git a/app/src/protyle/index.ts b/app/src/protyle/index.tsindex 42212e6e7d..523f5112fb 100644--- a/app/src/protyle/index.ts+++ b/app/src/protyle/index.ts@@ -41,6 +41,7 @@ import {renderBacklink} from "./wysiwyg/renderBacklink";import {setEmpty} from "../mobile/util/setEmpty";/// #if MOBILEimport {removeMobileSecondaryEditor, unregisterMobileSecondaryEditor} from "../mobile/util/secondaryEditors";+import {destroyMobileBottomBacklinkPanel} from "../mobile/util/bottomBacklink";/// #endifimport {resize} from "./util/resize";import {getDocByScroll} from "./scroll/saveScroll";@@ -675,6 +676,7 @@ export class Protyle {public destroy() {this.destroyed = true;/// #if MOBILE+ destroyMobileBottomBacklinkPanel(this.protyle);unregisterMobileSecondaryEditor(this);/// #endifdestroy(this.protyle);diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.tsindex 8ea0aacf0b..aa94dd88ed 100644--- a/app/src/protyle/util/onGet.ts+++ b/app/src/protyle/util/onGet.ts@@ -50,6 +50,7 @@ import {beginPerformance} from "./performance";/// #if MOBILEimport {updateMobileTitleReadonly} from "./setEditMode";import {pauseMobileBarsScroll} from "../../mobile/util/mobileBars";+import {updateMobileBottomBacklinkPanel} from "../../mobile/util/bottomBacklink";/// #endifexport const onGet = (options: {@@ -495,6 +496,11 @@ const setHTML = (options: {protyle.breadcrumb.toggleExit(!options.action.includes(Constants.CB_GET_ALL));protyle.breadcrumb.render(protyle);}+ /// #if MOBILE+ if (window.siyuan.mobile?.editor?.protyle === protyle) {+ void updateMobileBottomBacklinkPanel(protyle).catch(error => console.error(error));+ }+ /// #endifif (options.afterCB) {options.afterCB();}diff --git a/app/src/protyle/util/onGetMobileTopBar.test.ts b/app/src/protyle/util/onGetMobileTopBar.test.tsindex 53afd18f46..c9afea0735 100644--- a/app/src/protyle/util/onGetMobileTopBar.test.ts+++ b/app/src/protyle/util/onGetMobileTopBar.test.ts@@ -84,6 +84,7 @@ const browserCases = (code: typeof sources) => {isValid: () => true, action: [], afterOpen: () => {opened++;}, onFailure: () => {failed++;},sanitizeKernelHTML: (html: string) => html,beginPerformance: noop,+ updateMobileBottomBacklinkPanel: () => Promise.resolve(),};for (const name of ["invalidateTrackedRanges", "hideElements", "invalidateHeadingNumberRefresh","normalizeHTMLAssetIFrameSources", "updateWidgetCacheVersion", "disposeCustomBlocksInElement",@@ -145,6 +146,7 @@ test("mobile loading completion clears row navigation before settling once", ()document: {getElementById: (): HTMLElement | null => null},setEditor: () => calls.push("show editor"),bindMobileBarsScroll: () => calls.push("bind scroll"),+ updateMobileBottomBacklinkPanel: () => { calls.push("update backlinks"); return Promise.resolve(); },isValid: () => true,action: [] as string[], Constants: {CB_GET_OPENNEW: "open-new"},afterOpen: () => calls.push("opened"),@@ -155,7 +157,7 @@ test("mobile loading completion clears row navigation before settling once", ()const protyle = {element: container, contentElement: {}};complete(protyle);complete(protyle);- assert.deepEqual(calls, ["remove navigation", "protyle--database-row-navigation", "show editor", "bind scroll", "opened"]);+ assert.deepEqual(calls, ["remove navigation", "protyle--database-row-navigation", "show editor", "update backlinks", "bind scroll", "opened"]);});test("document rendering preserves landscape title controls and finishes loading", {