дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 01:01:17 +02:00
fix(editor): restore the caret and scroll of files whose tab was closed (#7641)
Closing a file's tab and reopening it later came back at line 1: saveSession() built its files map from the open slots only, so a disposed slot's caret and scroll were gone at the next save, and the live Markdown source dropped the whole per-path preview state on docClosed. The controller now remembers the view state of a file that loses its last tab (untitled buffers skipped, LRU-bounded at 200), persists it in an optional `closed` map of the editor session next to `files`, and applies it once when the file opens again. An open tab's live state always wins, a navigation target still overrides the remembered position, deleted files drop their entry, and older session files load unchanged. The Markdown preview keeps its position and zoom across the close and drops only the rendered text. Closes #7531 Co-authored-by: koeria <[email protected]>
Цей коміт міститься в:
1 джерело
355d6005aa
коміт
159f10ba82
5 files changed
+131
-11
No files matched your search
@@ -243,6 +243,9 @@ function isTextTab(tab: Tab | null | undefined): tab is Tab & { input: { path: s
|
||||
return !!tab && isTextInput(tab.input);
|
||||
}
|
||||
|
||||
/** Remembered view states of closed files, least-recently-used evicted past this. */
|
||||
const CLOSED_VIEWS_CAP = 200;
|
||||
|
||||
/** Keys of untitled buffers whose last tab the transition `before` → `after` closes. */
|
||||
function closedUntitledKeys(before: TabsState, after: TabsState): string[] {
|
||||
const open = openKeys(after);
|
||||
@@ -338,6 +341,8 @@ export class EditorController implements SlotHost {
|
||||
private sessionTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
/** Restored caret / scroll per path, applied when the file's first slot is created. */
|
||||
private restoredViews = new Map<string, FileViewState>();
|
||||
/** Last caret / scroll of files whose tab is no longer open (LRU-bounded), restored once on reopen. */
|
||||
private closedViews = new Map<string, FileViewState>();
|
||||
/** Tabs created by session restore; dropped silently if their file is gone. */
|
||||
private restoredTabs = new Set<string>();
|
||||
/** When each input key was last the active tab (a counter, across panes). */
|
||||
@@ -493,6 +498,7 @@ export class EditorController implements SlotHost {
|
||||
this.edits.clear();
|
||||
this.restoredTabs.clear();
|
||||
this.restoredViews.clear();
|
||||
this.closedViews.clear();
|
||||
this.projectTransition = this.releaseDocuments(documents.values())
|
||||
.catch((e) => this.documentError(e))
|
||||
.then(() => {
|
||||
@@ -585,6 +591,19 @@ export class EditorController implements SlotHost {
|
||||
if (!live.has(id)) {
|
||||
this.slots.delete(id);
|
||||
if (this.activeSlot === slot) this.setActiveSlot(null);
|
||||
// Remember the view state of a file that loses its last tab, so
|
||||
// reopening it can come back where it was (IDEA's editor history).
|
||||
const path = slot.model.path;
|
||||
if (path && !isUntitledUri(path)) {
|
||||
const state = slot.viewState();
|
||||
this.closedViews.delete(path);
|
||||
this.closedViews.set(path, state);
|
||||
while (this.closedViews.size > CLOSED_VIEWS_CAP) {
|
||||
const oldest = this.closedViews.keys().next().value;
|
||||
if (oldest === undefined) break;
|
||||
this.closedViews.delete(oldest);
|
||||
}
|
||||
}
|
||||
slot.dispose();
|
||||
}
|
||||
}
|
||||
@@ -685,6 +704,9 @@ export class EditorController implements SlotHost {
|
||||
if (files[path] && slot.model.lastFocused !== slot && !this.restoredViews.has(path)) continue;
|
||||
files[path] = slot.viewState();
|
||||
}
|
||||
// Files without an open tab: their last state is remembered, but an open
|
||||
// tab's live view state wins (serializeSession splits `files` by layout).
|
||||
for (const [path, state] of this.closedViews) if (!files[path]) files[path] = state;
|
||||
const kinds = useContributions.getState().editorKinds;
|
||||
storeSession(
|
||||
root,
|
||||
@@ -737,6 +759,7 @@ export class EditorController implements SlotHost {
|
||||
const current = useTabs.getState();
|
||||
const liveKeys = openKeys(current);
|
||||
this.restoredViews = new Map(Object.entries(session.files).filter(([path]) => !liveKeys.has(fileKey(path))));
|
||||
this.closedViews = new Map(Object.entries(session.closed ?? {}).filter(([path]) => !liveKeys.has(fileKey(path))));
|
||||
this.restoredTabs = new Set(Object.values(state.panes).flatMap((p) => p.tabs.map((t) => t.id)));
|
||||
this.restoring = true;
|
||||
try {
|
||||
@@ -822,6 +845,7 @@ export class EditorController implements SlotHost {
|
||||
// A file from the saved session no longer exists: drop its tab quietly.
|
||||
this.restoredTabs.delete(tabId);
|
||||
this.restoredViews.delete(path);
|
||||
this.closedViews.delete(path);
|
||||
const loc = this.locateTab(tabId);
|
||||
if (loc) this.apply((st) => (st.panes[loc.paneId] ? closeTab(st, loc.paneId, tabId) : st));
|
||||
return null;
|
||||
@@ -844,6 +868,14 @@ export class EditorController implements SlotHost {
|
||||
if (restored && !from) {
|
||||
this.restoredViews.delete(model.path);
|
||||
slot.restoreView(restored);
|
||||
} else if (!from) {
|
||||
// A file that lost its tab comes back where it was; the entry is spent,
|
||||
// so a second reopen starts at the top.
|
||||
const closed = this.closedViews.get(model.path);
|
||||
if (closed) {
|
||||
this.closedViews.delete(model.path);
|
||||
slot.restoreView(closed);
|
||||
}
|
||||
}
|
||||
this.restoredTabs.delete(tabId);
|
||||
const active = this.activeTabOf();
|
||||
@@ -2379,6 +2411,10 @@ export class EditorController implements SlotHost {
|
||||
|
||||
private onFilesRemoved(removed: string[]) {
|
||||
if (!removed.length) return;
|
||||
// A deleted (or renamed-away) file has no state worth remembering.
|
||||
for (const root of removed)
|
||||
for (const path of [...this.closedViews.keys()])
|
||||
if (path === root || path.startsWith(`${root}/`)) this.closedViews.delete(path);
|
||||
const kinds = useContributions.getState().editorKinds;
|
||||
const inputs = new Map<string, EditorInput>();
|
||||
for (const pane of Object.values(useTabs.getState().panes))
|
||||
|
||||
@@ -103,6 +103,57 @@ describe("editor session", () => {
|
||||
expect(junk.layout).toEqual({ kind: "pane", tabs: [{ input: { kind: "x", key: "y" } }], active: 0 });
|
||||
});
|
||||
|
||||
it("remembers the view state of files whose tab is not open", () => {
|
||||
let s = initialTabsState();
|
||||
s = open(s, "/p/a.ts");
|
||||
const session = serializeSession(
|
||||
s,
|
||||
{
|
||||
"/p/a.ts": { anchor: 3, head: 5, topLine: 10 },
|
||||
// No open tab any more: kept as a closed-file record, not a live one.
|
||||
"/p/closed.md": { anchor: 40, head: 40, topLine: 90 },
|
||||
"/p/gone.ts": { anchor: 1, head: 2 },
|
||||
},
|
||||
undefined,
|
||||
() => false,
|
||||
)!;
|
||||
expect(Object.keys(session.files)).toEqual(["/p/a.ts"]);
|
||||
expect(session.closed).toEqual({
|
||||
"/p/closed.md": { anchor: 40, head: 40, topLine: 90 },
|
||||
"/p/gone.ts": { anchor: 1, head: 2 },
|
||||
});
|
||||
|
||||
const parsed = parseSession(JSON.parse(JSON.stringify(session)))!;
|
||||
expect(parsed.closed).toEqual(session.closed);
|
||||
// An open tab wins: its path never moves into `closed`.
|
||||
expect(parsed.files).toEqual({ "/p/a.ts": { anchor: 3, head: 5, topLine: 10 } });
|
||||
|
||||
// A file that becomes open again loses its closed-file record.
|
||||
const reopened = initialTabsState();
|
||||
const withTab = open(open(reopened, "/p/a.ts"), "/p/closed.md");
|
||||
const saved = serializeSession(withTab, {
|
||||
"/p/a.ts": { anchor: 0, head: 0 },
|
||||
"/p/closed.md": { anchor: 1, head: 1 },
|
||||
})!;
|
||||
expect(saved.closed).toBeUndefined();
|
||||
expect(Object.keys(saved.files).sort()).toEqual(["/p/a.ts", "/p/closed.md"]);
|
||||
});
|
||||
|
||||
it("loads an older session file without closed-file records", () => {
|
||||
const raw = {
|
||||
version: 1,
|
||||
layout: { kind: "pane", tabs: [{ path: "/p/a.ts" }], active: 0 },
|
||||
activePane: 0,
|
||||
files: { "/p/a.ts": { anchor: 1, head: 2 } },
|
||||
};
|
||||
const parsed = parseSession(JSON.parse(JSON.stringify(raw)))!;
|
||||
expect(parsed.files).toEqual(raw.files);
|
||||
expect(parsed.closed).toBeUndefined();
|
||||
// Junk closed entries are dropped, and none are invented.
|
||||
expect(parseSession({ ...raw, closed: { "/p/b.ts": { anchor: -1, head: 0 } } })!.closed).toBeUndefined();
|
||||
expect(parseSession({ ...raw, closed: "nope" })!.closed).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns null for sessions without file tabs and rejects junk", () => {
|
||||
expect(serializeSession(initialTabsState(), {})).toBeNull();
|
||||
expect(parseSession({ version: 2 })).toBeNull();
|
||||
|
||||
@@ -39,6 +39,11 @@ export interface EditorSession {
|
||||
/** Index of the active pane in visual (depth-first) order. */
|
||||
activePane: number;
|
||||
files: Record<string, FileViewState>;
|
||||
/**
|
||||
* Last caret / scroll of files whose tab is no longer open, applied once when
|
||||
* the file opens again (like IDEA's editor history). Older sessions omit it.
|
||||
*/
|
||||
closed?: Record<string, FileViewState>;
|
||||
}
|
||||
|
||||
const STORAGE_PREFIX = "openidea.editorSession.v1:";
|
||||
@@ -91,8 +96,19 @@ export function serializeSession(
|
||||
l.kind === "pane" ? l.tabs.forEach((t) => t.path && paths.add(t.path)) : l.children.forEach(collect);
|
||||
collect(layout);
|
||||
const keptFiles: Record<string, FileViewState> = {};
|
||||
for (const p of paths) if (files[p]) keptFiles[p] = files[p]!;
|
||||
return { version: 1, layout, activePane, files: keptFiles };
|
||||
const closedFiles: Record<string, FileViewState> = {};
|
||||
for (const [p, v] of Object.entries(files)) {
|
||||
// An open tab always wins: only files without a saved tab keep their state.
|
||||
if (paths.has(p)) keptFiles[p] = v;
|
||||
else closedFiles[p] = v;
|
||||
}
|
||||
return {
|
||||
version: 1,
|
||||
layout,
|
||||
activePane,
|
||||
files: keptFiles,
|
||||
...(Object.keys(closedFiles).length ? { closed: closedFiles } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -138,23 +154,28 @@ export function parseSession(raw: unknown): EditorSession | null {
|
||||
};
|
||||
const layout = check(r.layout, 0);
|
||||
if (!layout) return null;
|
||||
const files: Record<string, FileViewState> = {};
|
||||
if (r.files && typeof r.files === "object") {
|
||||
for (const [path, v] of Object.entries(r.files)) {
|
||||
const readViews = (record: unknown): Record<string, FileViewState> => {
|
||||
const out: Record<string, FileViewState> = {};
|
||||
if (!record || typeof record !== "object") return out;
|
||||
for (const [path, v] of Object.entries(record)) {
|
||||
const f = v as Partial<FileViewState> | null;
|
||||
if (f && Number.isInteger(f.anchor) && Number.isInteger(f.head) && f.anchor! >= 0 && f.head! >= 0)
|
||||
files[slashPath(path)] = {
|
||||
out[slashPath(path)] = {
|
||||
anchor: f.anchor!,
|
||||
head: f.head!,
|
||||
...(Number.isInteger(f.topLine) && f.topLine! >= 0 ? { topLine: f.topLine } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
const files = readViews(r.files);
|
||||
const closed = readViews(r.closed);
|
||||
return {
|
||||
version: 1,
|
||||
layout,
|
||||
activePane: typeof r.activePane === "number" ? Math.max(0, Math.floor(r.activePane)) : 0,
|
||||
files,
|
||||
...(Object.keys(closed).length ? { closed } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -33,12 +33,21 @@ describe("Markdown source scroll", () => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("releases parsed preview source when the document closes", () => {
|
||||
it("releases parsed preview source when the document closes, keeping the position", () => {
|
||||
const other = { ...useLiveMarkdown.getState()[ctx.path]!, previewTop: 52 };
|
||||
useLiveMarkdown.setState({ "/p/other.md": other });
|
||||
expect(useLiveMarkdown.getState()[ctx.path]?.text).toBe(view.state.doc);
|
||||
const before = useLiveMarkdown.getState()[ctx.path]!;
|
||||
_emitEditorEvent({ type: "docClosed", doc: ctx.doc, path: ctx.path });
|
||||
expect(useLiveMarkdown.getState()).toEqual({ "/p/other.md": other });
|
||||
const kept = useLiveMarkdown.getState()[ctx.path];
|
||||
// The rendered text is dropped, but the scroll / zoom state survives for a reopen.
|
||||
expect(kept).toEqual({ ...before, text: expect.anything(), edit: null, find: null });
|
||||
expect((kept as { text: { length: number } }).text.length).toBe(0);
|
||||
expect(kept?.topLine).toBe(before.topLine);
|
||||
expect(kept?.previewTop).toBe(before.previewTop);
|
||||
expect(kept?.fontZoom).toBe(before.fontZoom);
|
||||
// A never-opened path gains nothing.
|
||||
expect(useLiveMarkdown.getState()["/p/none.md"]).toBeUndefined();
|
||||
});
|
||||
|
||||
function sourceBlock(lineNumber: number, top: number, height: number): BlockInfo {
|
||||
|
||||
@@ -386,9 +386,12 @@ export function registerMarkdownLiveSource(): () => void {
|
||||
if (event.type !== "docClosed") return;
|
||||
const { path } = event;
|
||||
useLiveMarkdown.setState((state) => {
|
||||
if (!state[path]) return state;
|
||||
const prev = state[path];
|
||||
if (!prev) return state;
|
||||
const next = { ...state };
|
||||
delete next[path];
|
||||
// Keep the preview's position (and font zoom) so a file that lost its
|
||||
// tab can come back where it was; only the rendered text is dropped.
|
||||
next[path] = { ...prev, text: Text.empty, edit: null, find: null };
|
||||
return next;
|
||||
}, true);
|
||||
});
|
||||
|
||||
Reference in new issue
Заблокувати користувача