## 前提 [[Obsidian]]のバージョンは1.9.14。 ## 方法 [[ワークスペース (Obsidian)|ワークスペース]]切り替え時に `ViewState` と `EphemeralState` を保存しておき、切り替え後に復元する。 ```ts import type { ViewState } from "obsidian"; import { getActiveLeaf, getAllMarkdownLeaves, setActiveLeaf, } from "src/lib/helpers/leaves"; import { notifyRuntimeError } from "src/lib/helpers/ui"; import { moveNextWorkspace as _moveToNextWorkspace, getActiveWorkspaceName, } from "src/lib/helpers/workspace"; const workspaceEditorState: { [workspaceName: string]: | { leaves: { vState: ViewState; eState: any }[]; activeLeafIndex: number | undefined; } | undefined; } = {}; /** * 次のワークスペースに移動する(循環) */ export async function moveToNextWorkspace() { const previousLeaves = getAllMarkdownLeaves(); workspaceEditorState[getActiveWorkspaceName()] = { leaves: previousLeaves.map((leaf) => { return { vState: { ...leaf.getViewState() }, eState: { ...leaf.getEphemeralState() }, }; }), activeLeafIndex: previousLeaves.findIndex( (x) => x.id === getActiveLeaf()?.id, ), }; try { await _moveToNextWorkspace({ saveActiveWorkspace: true }); } catch (error: any) { return notifyRuntimeError(error.message); } const previousState = workspaceEditorState[getActiveWorkspaceName()]; if (!previousState) { return; } const currentLeaves = getAllMarkdownLeaves(); for (const [i, leaf] of currentLeaves.entries()) { leaf.setViewState( previousState.leaves[i].vState, previousState.leaves[i].eState, ); } // リーフの復元が完了してからアクティブリーフを設定するために待機 await sleep(0); if (previousState.activeLeafIndex == null) { return; } const activeLeaf = getAllMarkdownLeaves()[previousState.activeLeafIndex]; if (activeLeaf) { setActiveLeaf(activeLeaf); } } ``` `src/lib/helpers/workspace.ts` ```ts /** * 現在のワークスペース名を取得します */ export function getActiveWorkspaceName(): string { const ws = app.internalPlugins.plugins.workspaces; if (!ws.enabled) { throw Error("Workspacesプラグインが有効化されていません"); } return ws.instance.activeWorkspace; } /** * 次のワークスペースに移動します(循環) * @param opts * - saveActiveWorkspace: 現在のワークスペースを保存するかどうか(デフォルト: false) * */ export async function moveNextWorkspace(opts?: { saveActiveWorkspace?: boolean; }): Promise<void> { const ws = app.internalPlugins.plugins.workspaces; if (!ws.enabled) { throw Error("Workspacesプラグインが有効化されていません"); } const wss = ws.instance; const { saveActiveWorkspace = false } = opts ?? {}; const wsEntries = Object.entries(wss.workspaces); const activeWsKey = wss.activeWorkspace; const activeIndex = wsEntries.findIndex(([k]) => k === activeWsKey); const nextIndex = (activeIndex + 1) % wsEntries.length; const nextWsKey = wsEntries[nextIndex][0]; if (saveActiveWorkspace) { await wss.saveWorkspace(activeWsKey); } await wss.loadWorkspace(nextWsKey); } ``` 詳しくは[[🦉Carnelian]]の最新実装を確認。