An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Stabilize mobile tab navigation https://github.com/siyuan-note/siyuan/issues/16094
Daniel09cb7fa9948d
diff --git a/app/src/mobile/editor.ts b/app/src/mobile/editor.tsindex 3fb74aa5d8..d763a546be 100644--- a/app/src/mobile/editor.ts+++ b/app/src/mobile/editor.ts@@ -58,8 +58,25 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[scrollPosition?: ScrollLogicalPosition, notebookId?: string,afterOpen?: (protyle: IProtyle) => void, forceReload = false,isValid: () => boolean = () => true, signal?: AbortSignal,- scrollAttr?: IScrollAttr, updateRecent = true) => {+ scrollAttr?: IScrollAttr, updateRecent = true,+ onFailure?: (invalid?: boolean) => void) => {+ let completed = false;+ const complete = (protyle: IProtyle) => {+ if (completed) {+ return;+ }+ completed = true;+ afterOpen?.(protyle);+ };+ const fail = (invalid = false) => {+ if (completed) {+ return;+ }+ completed = true;+ onFailure?.(invalid);+ };if (!isValid()) {+ fail();return;}const avPanelElement = document.querySelector(".av__panel");@@ -95,7 +112,7 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[if (updateRecent) {updateRecentDocSwitchTime(createRecentDocUpdate(rootID, rootID));}- afterOpen?.(protyle);+ complete(protyle);return;}}@@ -105,12 +122,20 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[if (isEncryptedBox(targetNotebookId)) {blockInfoParam.notebook = targetNotebookId;}- fetchPost("/api/block/getBlockInfo", blockInfoParam, (data) => {+ let blockInfoHandled = false;+ void fetchPost("/api/block/getBlockInfo", blockInfoParam, (data) => {+ blockInfoHandled = true;if (!isValid()) {+ fail();return;}if (data.code === 3) {showMessage(data.msg);+ fail(true);+ return;+ }+ if (data.code !== 0 || !data.data?.rootID) {+ fail();return;}const isRootFocus = id === data.data.rootID &&@@ -138,12 +163,13 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[},after: (editor) => {if (!isValid()) {+ fail();return;}if (updateRecent) {updateRecentDocSwitchTime(createRecentDocUpdate(data.data.rootID, previousRootID));}- afterOpen?.(editor.protyle);+ complete(editor.protyle);},};if (window.siyuan.mobile.editor) {@@ -160,8 +186,10 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[scrollAttr: targetScrollAttr,mergedOptions: protyleOptions,signal,+ fail,cb() {if (!isValid()) {+ fail();return;}if (updateRecent) {@@ -170,7 +198,7 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[app.plugins.forEach(item => {item.eventBus.emit("switch-protyle", {protyle: window.siyuan.mobile.editor.protyle});});- afterOpen?.(window.siyuan.mobile.editor.protyle);+ complete(window.siyuan.mobile.editor.protyle);}});} else {@@ -182,29 +210,49 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[if (isEncryptedBox(window.siyuan.mobile.editor.protyle.notebookId)) {getDocParam.notebook = window.siyuan.mobile.editor.protyle.notebookId;}- fetchPost("/api/filetree/getDoc", getDocParam, getResponse => {+ let getDocHandled = false;+ void fetchPost("/api/filetree/getDoc", getDocParam, getResponse => {+ getDocHandled = true;if (!isValid()) {+ fail();return;}- onGet({- data: getResponse,- protyle: window.siyuan.mobile.editor.protyle,- action: actionList,- scrollPosition,- afterCB() {- if (!isValid()) {- return;- }- if (updateRecent) {- updateRecentDocSwitchTime(createRecentDocUpdate(data.data.rootID, previousRootID));+ if (getResponse.code !== 0 && onFailure) {+ fail(true);+ return;+ }+ try {+ onGet({+ data: getResponse,+ protyle: window.siyuan.mobile.editor.protyle,+ action: actionList,+ scrollPosition,+ afterCB() {+ if (!isValid()) {+ fail();+ return;+ }+ if (updateRecent) {+ updateRecentDocSwitchTime(createRecentDocUpdate(data.data.rootID, previousRootID));+ }+ app.plugins.forEach(item => {+ item.eventBus.emit("switch-protyle", {protyle: window.siyuan.mobile.editor.protyle});+ });+ complete(window.siyuan.mobile.editor.protyle);}- app.plugins.forEach(item => {- item.eventBus.emit("switch-protyle", {protyle: window.siyuan.mobile.editor.protyle});- });- afterOpen?.(window.siyuan.mobile.editor.protyle);- }- });- }, undefined, undefined, signal);+ });+ } catch (error) {+ console.error(error);+ fail();+ }+ if (!completed) {+ fail();+ }+ }, undefined, undefined, signal).then(() => {+ if (!getDocHandled) {+ fail();+ }+ });}window.siyuan.mobile.editor.protyle.undo.clear();// 切换文档后校准新文档的撤销镜像(语义 B:各文档栈隔离)@@ -212,11 +260,21 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[initMirror(window.siyuan.mobile.editor.protyle.block.rootID);}} else {- window.siyuan.mobile.editor = new Protyle(app, document.getElementById("editor"), protyleOptions);+ try {+ window.siyuan.mobile.editor = new Protyle(app, document.getElementById("editor"), protyleOptions);+ } catch (error) {+ console.error(error);+ fail();+ return;+ }}setEditor();closePanel();- }, undefined, undefined, signal);+ }, undefined, undefined, signal).then(() => {+ if (!blockInfoHandled) {+ fail();+ }+ });};export const openMobileFileById = (app: App, id: string, action: TProtyleAction[] = [Constants.CB_GET_HL],@@ -225,9 +283,17 @@ export const openMobileFileById = (app: App, id: string, action: TProtyleAction[if (window.siyuan.mobile.tabs) {const options = {action, scrollPosition, notebookId, afterOpen, forceReload};if (action.includes(Constants.CB_GET_OPENNEW)) {- void window.siyuan.mobile.tabs.openInNewTab(id, options);+ void window.siyuan.mobile.tabs.openInNewTab(id, options).then((result) => {+ if (result === "invalid" || result === "failed") {+ void window.siyuan.mobile.tabs.restore();+ }+ });} else {- void window.siyuan.mobile.tabs.open(id, options);+ void window.siyuan.mobile.tabs.open(id, options).then((result) => {+ if (result === "invalid" || result === "failed") {+ void window.siyuan.mobile.tabs.restore();+ }+ });}return;}@@ -241,7 +307,16 @@ export const openMobileFileByIdInNewTab = (app: App, id: string,scrollPosition?: ScrollLogicalPosition, notebookId?: string,afterOpen?: (protyle: IProtyle) => void) => {if (window.siyuan.mobile.tabs) {- void window.siyuan.mobile.tabs.openInNewTab(id, {action, scrollPosition, notebookId, afterOpen});+ void window.siyuan.mobile.tabs.openInNewTab(id, {+ action,+ scrollPosition,+ notebookId,+ afterOpen+ }).then((result) => {+ if (result === "invalid" || result === "failed") {+ void window.siyuan.mobile.tabs.restore();+ }+ });} else {openMobileFileById(app, id, action, scrollPosition, notebookId, afterOpen);}diff --git a/app/src/mobile/tabs/MobileTabs.ts b/app/src/mobile/tabs/MobileTabs.tsindex fa7f4e3888..88de92ac4b 100644--- a/app/src/mobile/tabs/MobileTabs.ts+++ b/app/src/mobile/tabs/MobileTabs.ts@@ -50,6 +50,11 @@ type OpenOptions = {recentPreviousRootID?: string;};+type MobileTabOpenResult = "success" | "cancelled" | "invalid" | "failed";++class InvalidMobileTabTargetError extends Error {+}+const isEntry = (value: unknown): value is MobileTabEntry => {const entry = value as MobileTabEntry;return !!entry && typeof entry.id === "string" && typeof entry.rootID === "string" &&@@ -192,17 +197,23 @@ export class MobileTabs {if (notebookId) {data.notebook = notebookId;}- fetchPost("/api/block/getBlockInfo", data, (response) => {+ let handled = false;+ void fetchPost("/api/block/getBlockInfo", data, (response) => {+ handled = true;if (response.code === 0 && response.data?.rootID) {resolve(response.data);} else {- reject(new Error(response.msg));+ reject(new InvalidMobileTabTargetError(response.msg));}- }, undefined, undefined, signal);+ }, undefined, undefined, signal).then(() => {+ if (!handled && !signal?.aborted) {+ reject(new Error("Failed to resolve mobile tab target"));+ }+ });});}- async open(id: string, options: OpenOptions = {}) {+ async open(id: string, options: OpenOptions = {}): Promise<MobileTabOpenResult> {const action = options.action || [Constants.CB_GET_HL];this.abortController?.abort();const abortController = new AbortController();@@ -211,11 +222,14 @@ export class MobileTabs {let info: {rootID: string; box: string};try {info = await this.resolveRoot(id, options.notebookId, abortController.signal);- } catch {- return abortController.signal.aborted;+ } catch (error) {+ if (abortController.signal.aborted) {+ return "cancelled";+ }+ return error instanceof InvalidMobileTabTargetError ? "invalid" : "failed";}if (epoch !== this.navigationEpoch) {- return true;+ return "cancelled";}this.snapshot();@@ -240,45 +254,65 @@ export class MobileTabs {};}const previous = tab.current;- const loadID = switchedExisting && previous ? previous.id : id;- const loadAction = switchedExisting ? [Constants.CB_GET_SCROLL] as TProtyleAction[] : action;- const loadScroll = switchedExisting ? previous?.scroll : options.scroll;- const shouldReplace = options.replace || switchedExisting || previous?.id === id;+ const restoreExistingPosition = switchedExisting && id === info.rootID &&+ action.includes(Constants.CB_GET_SCROLL);+ const loadID = restoreExistingPosition && previous ? previous.id : id;+ const loadAction = restoreExistingPosition ? [Constants.CB_GET_SCROLL] as TProtyleAction[] : action;+ const loadScroll = restoreExistingPosition ? previous?.scroll : options.scroll;+ const shouldReplace = options.replace || restoreExistingPosition || previous?.id === id;const targetTabID = tab.id;- loadMobileFileById(this.app, loadID, loadAction, options.scrollPosition, info.box, (protyle) => {- if (epoch !== this.navigationEpoch || targetTabID !== tab.id) {- return;- }- if (!shouldReplace) {- this.pushHistory(tab.backStack, previous);- tab.forwardStack = [];- }- if (createOnSuccess) {- this.state.tabs.push(tab);- }- tab.current = this.entryFromProtyle(loadID, loadAction, protyle);- tab.activeAt = Date.now();- this.state.activeTabID = tab.id;- this.trimTabs();- window.siyuan.storage[Constants.LOCAL_DOCINFO] = {id: loadID};- setStorageVal(Constants.LOCAL_DOCINFO, {id: loadID});- this.persist();- this.updateCounter();- const previousRootID = options.recentPreviousRootID || previous?.rootID;- if (switchedExisting || previousRootID === protyle.block.rootID) {- updateRecentDocSwitchTime({type: "view", rootID: protyle.block.rootID});- } else if (previousRootID) {- updateRecentDocSwitchTime({- type: "switch",- rootID: protyle.block.rootID,- previousRootID,- });- } else {- updateRecentDocSwitchTime({type: "open", rootID: protyle.block.rootID});- }- options.afterOpen?.(protyle);- }, options.forceReload, () => epoch === this.navigationEpoch, abortController.signal, loadScroll, false);- return true;+ return new Promise<MobileTabOpenResult>((resolve) => {+ let settled = false;+ const finish = (result: MobileTabOpenResult) => {+ if (settled) {+ return;+ }+ settled = true;+ resolve(result);+ };+ abortController.signal.addEventListener("abort", () => finish("cancelled"), {once: true});+ loadMobileFileById(this.app, loadID, loadAction, options.scrollPosition, info.box, (protyle) => {+ if (epoch !== this.navigationEpoch) {+ finish("cancelled");+ return;+ }+ if (!createOnSuccess && !this.state.tabs.some((item) => item.id === targetTabID)) {+ finish("cancelled");+ return;+ }+ if (!shouldReplace) {+ this.pushHistory(tab.backStack, previous);+ tab.forwardStack = [];+ }+ if (createOnSuccess) {+ this.state.tabs.push(tab);+ }+ tab.current = this.entryFromProtyle(loadID, loadAction, protyle);+ tab.activeAt = Date.now();+ this.state.activeTabID = tab.id;+ this.trimTabs();+ window.siyuan.storage[Constants.LOCAL_DOCINFO] = {id: loadID};+ setStorageVal(Constants.LOCAL_DOCINFO, {id: loadID});+ this.persist();+ this.updateCounter();+ const previousRootID = options.recentPreviousRootID || previous?.rootID;+ if (switchedExisting || previousRootID === protyle.block.rootID) {+ updateRecentDocSwitchTime({type: "view", rootID: protyle.block.rootID});+ } else if (previousRootID) {+ updateRecentDocSwitchTime({+ type: "switch",+ rootID: protyle.block.rootID,+ previousRootID,+ });+ } else {+ updateRecentDocSwitchTime({type: "open", rootID: protyle.block.rootID});+ }+ finish("success");+ options.afterOpen?.(protyle);+ }, options.forceReload, () => epoch === this.navigationEpoch, abortController.signal, loadScroll, false, (invalid) => {+ finish(abortController.signal.aborted ? "cancelled" : (invalid ? "invalid" : "failed"));+ });+ });}openInNewTab(id: string, options: Omit<OpenOptions, "newTab"> = {}) {@@ -298,7 +332,7 @@ export class MobileTabs {this.updateCounter();return true;}- const launched = await this.open(tab.current.id, {+ const result = await this.open(tab.current.id, {action: [Constants.CB_GET_SCROLL],notebookId: tab.current.notebookID,forceReload: true,@@ -306,13 +340,16 @@ export class MobileTabs {scroll: tab.current.scroll,tabID: tab.id,});- if (!launched) {+ if (result === "invalid") {this.state.tabs = this.state.tabs.filter((item) => item.id !== tab.id);this.state.activeTabID = [...this.state.tabs].sort((a, b) => b.activeAt - a.activeAt)[0]?.id;this.persist();this.updateCounter();return this.restore();}+ if (result === "failed") {+ setEmpty(this.app);+ }return true;}@@ -346,13 +383,11 @@ export class MobileTabs {const tab = this.state.tabs.find((item) => item.id === tabID);if (!tab || tab.id === this.state.activeTabID) {closeModel();- return;+ return !!tab;}this.snapshot();- this.state.activeTabID = tab.id;- tab.activeAt = Date.now();if (tab.current) {- await this.open(tab.current.id, {+ const result = await this.open(tab.current.id, {action: [Constants.CB_GET_SCROLL],notebookId: tab.current.notebookID,forceReload: true,@@ -360,13 +395,20 @@ export class MobileTabs {scroll: tab.current.scroll,tabID: tab.id,});+ if (result === "invalid" || result === "failed") {+ await this.restore();+ return false;+ }} else {this.cancelNavigation();+ this.state.activeTabID = tab.id;+ tab.activeAt = Date.now();setEmpty(this.app);this.persist();this.updateCounter();}closeModel();+ return true;}async goBack(): Promise<boolean> {@@ -381,7 +423,7 @@ export class MobileTabs {this.pushHistory(tab.forwardStack, tab.current);tab.current = target;this.persist();- const launched = await this.open(target.id, {+ const result = await this.open(target.id, {action: [Constants.CB_GET_SCROLL],notebookId: target.notebookID,forceReload: true,@@ -390,11 +432,14 @@ export class MobileTabs {tabID: tab.id,recentPreviousRootID: previousRootID,});- if (!launched) {+ if (result === "invalid" || result === "failed") {tab.current = previous;tab.forwardStack.pop();this.persist();- return this.goBack();+ if (result === "invalid") {+ return this.goBack();+ }+ await this.restore();}return true;}@@ -411,7 +456,7 @@ export class MobileTabs {this.pushHistory(tab.backStack, tab.current);tab.current = target;this.persist();- const launched = await this.open(target.id, {+ const result = await this.open(target.id, {action: [Constants.CB_GET_SCROLL],notebookId: target.notebookID,forceReload: true,@@ -420,11 +465,14 @@ export class MobileTabs {tabID: tab.id,recentPreviousRootID: previousRootID,});- if (!launched) {+ if (result === "invalid" || result === "failed") {tab.current = previous;tab.backStack.pop();this.persist();- return this.goForward();+ if (result === "invalid") {+ return this.goForward();+ }+ await this.restore();}return true;}@@ -435,18 +483,27 @@ export class MobileTabs {return;}const wasActive = this.state.activeTabID === tabID;+ if (wasActive) {+ this.cancelNavigation();+ }const closedRootID = this.state.tabs[index].current?.rootID;this.state.tabs.splice(index, 1);if (closedRootID) {fetchPost("/api/storage/updateRecentDocCloseTime", {rootID: closedRootID});}if (wasActive) {+ this.state.activeTabID = undefined;const next = [...this.state.tabs].sort((a, b) => b.activeAt - a.activeAt)[0];if (next?.current) {- this.state.activeTabID = undefined;- await this.switchTo(next.id);+ const opened = await this.switchTo(next.id);+ if (!opened) {+ setEmpty(this.app);+ }} else {this.state.activeTabID = next?.id;+ if (next) {+ next.activeAt = Date.now();+ }setEmpty(this.app);}}@@ -483,6 +540,9 @@ export class MobileTabs {}removeRoots(rootIDs: string[]) {+ if (rootIDs.length === 0) {+ return;+ }const roots = new Set(rootIDs);this.state.tabs.forEach((tab) => {if (tab.current && roots.has(tab.current.rootID)) {@@ -493,12 +553,14 @@ export class MobileTabs {}private filterEntries(predicate: (entry: MobileTabEntry) => boolean) {+ const activeTabID = this.state.activeTabID;this.state.tabs.forEach((tab) => {tab.backStack = tab.backStack.filter(predicate);tab.forwardStack = tab.forwardStack.filter(predicate);});this.state.tabs = this.state.tabs.filter((tab) => !tab.current || predicate(tab.current));- if (!this.state.tabs.some((tab) => tab.id === this.state.activeTabID)) {+ if (!this.state.tabs.some((tab) => tab.id === activeTabID)) {+ this.cancelNavigation();this.state.activeTabID = [...this.state.tabs].sort((a, b) => b.activeAt - a.activeAt)[0]?.id;if (this.state.activeTabID) {void this.restore();diff --git a/app/src/protyle/scroll/saveScroll.ts b/app/src/protyle/scroll/saveScroll.tsindex 39133e4dfc..7403ef0dec 100644--- a/app/src/protyle/scroll/saveScroll.ts+++ b/app/src/protyle/scroll/saveScroll.ts@@ -64,11 +64,23 @@ export const getDocByScroll = (options: {protyle: IProtyle,scrollAttr?: IScrollAttr,mergedOptions?: IProtyleOptions,- cb?: (keys: string[]) => void+ cb?: (keys: string[]) => void,focus?: boolean,updateReadonly?: boolean,- signal?: AbortSignal+ signal?: AbortSignal,+ fail?: (invalid?: boolean) => void,}) => {+ const fetchDoc = (params: Record<string, any>, callback: (response: IWebSocketData) => void) => {+ let handled = false;+ void fetchPost("/api/filetree/getDoc", params, (response) => {+ handled = true;+ callback(response);+ }, undefined, undefined, options.signal).then(() => {+ if (!handled) {+ options.fail?.();+ }+ });+ };let actions: TProtyleAction[] = [];if (options.mergedOptions) {actions = options.mergedOptions.action;@@ -79,6 +91,30 @@ export const getDocByScroll = (options: {actions = [Constants.CB_GET_UNUNDO];}}+ const renderDoc = (response: IWebSocketData) => {+ let callbackCalled = false;+ try {+ onGet({+ scrollPosition: options.mergedOptions?.scrollPosition,+ data: response,+ protyle: options.protyle,+ action: actions,+ scrollAttr: options.scrollAttr,+ afterCB: options.cb ? () => {+ callbackCalled = true;+ options.cb(response.data.keywords);+ } : undefined,+ updateReadonly: options.updateReadonly+ });+ } catch (error) {+ console.error(error);+ options.fail?.();+ return;+ }+ if (options.cb && !callbackCalled) {+ options.fail?.();+ }+ };if (options.scrollAttr?.zoomInId && options.scrollAttr?.rootId && options.scrollAttr.zoomInId !== options.scrollAttr.rootId) {const getDocParam: Record<string, any> = {id: options.scrollAttr.zoomInId,@@ -92,7 +128,7 @@ export const getDocByScroll = (options: {if (isEncryptedBox(options.protyle.notebookId)) {getDocParam.notebook = options.protyle.notebookId;}- fetchPost("/api/filetree/getDoc", getDocParam, response => {+ fetchDoc(getDocParam, response => {if (response.code === 1) {const getDocParam: Record<string, any> = {id: options.scrollAttr.rootId || options.mergedOptions?.blockId || options.protyle.block?.rootID || options.scrollAttr.startId,@@ -105,34 +141,22 @@ export const getDocByScroll = (options: {if (isEncryptedBox(options.protyle.notebookId)) {getDocParam.notebook = options.protyle.notebookId;}- fetchPost("/api/filetree/getDoc", getDocParam, response => {- onGet({- scrollPosition: options.mergedOptions?.scrollPosition,- data: response,- protyle: options.protyle,- action: actions,- scrollAttr: options.scrollAttr,- afterCB: options.cb ? () => {- options.cb(response.data.keywords);- } : undefined,- updateReadonly: options.updateReadonly- });- }, undefined, undefined, options.signal);+ fetchDoc(getDocParam, response => {+ if (response.code !== 0 && options.fail) {+ options.fail(true);+ return;+ }+ renderDoc(response);+ });} else {+ if (response.code !== 0 && options.fail) {+ options.fail(true);+ return;+ }actions.push(Constants.CB_GET_ALL);- onGet({- scrollPosition: options.mergedOptions?.scrollPosition,- data: response,- protyle: options.protyle,- action: actions,- scrollAttr: options.scrollAttr,- afterCB: options.cb ? () => {- options.cb(response.data.keywords);- } : undefined,- updateReadonly: options.updateReadonly- });+ renderDoc(response);}- }, undefined, undefined, options.signal);+ });return;}const getDocParam: Record<string, any> = {@@ -148,17 +172,11 @@ export const getDocByScroll = (options: {if (isEncryptedBox(options.protyle.notebookId)) {getDocParam.notebook = options.protyle.notebookId;}- fetchPost("/api/filetree/getDoc", getDocParam, response => {- onGet({- scrollPosition: options.mergedOptions?.scrollPosition,- data: response,- protyle: options.protyle,- action: actions,- scrollAttr: options.scrollAttr,- afterCB: options.cb ? () => {- options.cb(response.data.keywords);- } : undefined,- updateReadonly: options.updateReadonly- });- }, undefined, undefined, options.signal);+ fetchDoc(getDocParam, response => {+ if (response.code !== 0 && options.fail) {+ options.fail(true);+ return;+ }+ renderDoc(response);+ });};diff --git a/app/src/util/reloadSync.ts b/app/src/util/reloadSync.tsindex 02eb664f86..b3b84f7438 100644--- a/app/src/util/reloadSync.ts+++ b/app/src/util/reloadSync.ts@@ -30,9 +30,9 @@ export const reloadSync = (window.siyuan.mobile.popEditor.reload(false, updateReadonly);}}+ window.siyuan.mobile.tabs?.removeRoots(data.removeRootIDs);if (document.getElementById("empty").classList.contains("fn__none") &&window.siyuan.mobile.editor && window.siyuan.mobile.editor.protyle) {- window.siyuan.mobile.tabs?.removeRoots(data.removeRootIDs);if (data.removeRootIDs.includes(window.siyuan.mobile.editor.protyle.block.rootID)) {if (!window.siyuan.mobile.tabs) {setEmpty(app);