diff --git a/src/editor/core/controller.test.ts b/src/editor/core/controller.test.ts index cb2e72390..799c1370d 100644 --- a/src/editor/core/controller.test.ts +++ b/src/editor/core/controller.test.ts @@ -203,6 +203,29 @@ describe("EditorController", () => { } }); + it("gives the keyboard to the next tab when the focused one closes", async () => { + ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "a\n", "/p/b.ts": "b\n" })); + ctrl.start(); + await ctrl.openFile("/p/a.ts", { focus: false }); + const first = ctrl.activeSlot!; + await ctrl.openFile("/p/b.ts", { focus: false }); + const second = ctrl.activeSlot!; + const hosts = [document.createElement("div"), document.createElement("div")]; + document.body.append(...hosts); + try { + const a = first.mount(hosts[0]!); + ctrl.onMounted(first); + const b = second.mount(hosts[1]!); + ctrl.onMounted(second); + b.focus(); + expect(b.hasFocus).toBe(true); + await ctrl.closeActiveTab(); + expect(a.hasFocus).toBe(true); + } finally { + hosts.forEach((h) => h.remove()); + } + }); + it("autosaves on blur, but not while focus is in a popup over the editor", async () => { const backend = createMemoryBackend({ "/p/a.c": "int main() {\n \n}\n" }); const save = vi.spyOn(backend, "save"); diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index 5fd984242..671e9cba5 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -1735,8 +1735,18 @@ export class EditorController implements SlotHost { }); } - closeTab(paneId: string, tabId: string): Promise { - return this.removeGuarded((s) => (s.panes[paneId] ? closeTab(s, paneId, tabId) : s)); + async closeTab(paneId: string, tabId: string): Promise { + const hadFocus = this.slots.get(tabId)?.view?.hasFocus ?? false; + const closed = await this.removeGuarded((s) => (s.panes[paneId] ? closeTab(s, paneId, tabId) : s)); + // The closed editor had the keyboard: hand it to the tab that took its place. + if (closed && hadFocus) await this.focusActiveEditor(); + return closed; + } + + private async focusActiveEditor() { + const tab = this.activeTabOf(); + if (tab) await this.ensureSlot(tab.id); + if (this.activeTabOf()?.id === tab?.id) this.focus(); } closeOthers(paneId: string, tabId: string): Promise { return this.removeGuarded((s) => (s.panes[paneId] ? closeOthers(s, paneId, tabId) : s), {