A1: tab management: preview tabs, pinning, close actions, reopen closed tab, split into two groups
Some checks are pending
ci / ci (macos-15) (push) Waiting to run
ci / ci (ubuntu-24.04) (push) Waiting to run
ci / ci (windows-2025) (push) Waiting to run

- Pure tab model (components/editor/tabs/model.ts) with Vitest coverage.
- Editor store keeps one buffer sync per buffer and a group layout; a buffer
  in both groups shares text and undo. Bulk closes ask once with a list.
- Tab context menu, tabs.* UI commands (COMMAND_IDS) in a Window menu group,
  no default shortcuts; Show Local History appears once history.show exists.
- Single click in the tree, Find and Go-to opens preview tabs.
- Layout stored through layout.set and restored on project open.
- Public API for other areas: tabOfPath, tabOf, reloadBuffer, openFile.
- Docs: ui-parity, gaps (G2), architecture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-11-08 12:18:28 +01:00
parent 02922eb89d
commit 7f309dbc4e
28 changed files with 3003 additions and 211 deletions

View file

@ -180,7 +180,7 @@ describe("one modal at a time", () => {
await mountApp();
const editor = useEditorStore(pinia);
await uiCommand("palette.open");
editor.closePrompt = { id: 1, name: "a.php" };
editor.closePrompt = { items: [{ id: 1, name: "a.php" }] };
await flushPromises();
expect(paletteShown()).toBe(false);
expect(useModalsStore(pinia).current).toBe("closePrompt");

View file

@ -0,0 +1,262 @@
/**
* Tests for the pure tab layout (C10 A1, `components/editor/tabs/model.ts`):
* preview replacement, pinning, bulk close targets, splitting, moving and
* joining groups, the stored layout and the reopen stack.
*/
import { describe, expect, it } from "vitest";
import {
activeBuffer,
closeTargets,
emptyLayout,
groupsOf,
keepOpen,
MAX_CLOSED,
moveToOtherGroup,
parseStored,
placeTab,
pushClosed,
removeBuffer,
removeTab,
setPinned,
split,
toStored,
unsplit,
type ClosedTab,
type TabLayout,
} from "../../src/components/editor/tabs/model";
/**
* A one-group layout with permanent tabs for the ids, the last one active.
*
* @param ids - buffer ids in order.
*/
function withTabs(...ids: number[]): TabLayout {
let layout = emptyLayout();
for (const id of ids) {
layout = placeTab(layout, 0, id, { preview: false, activate: true }).layout;
}
return layout;
}
/**
* The buffer ids of a group in order.
*
* @param layout - the layout.
* @param group - group index.
*/
function ids(layout: TabLayout, group = 0): number[] {
return layout.groups[group]?.tabs.map((t) => t.id) ?? [];
}
describe("placing tabs", () => {
it("inserts after the active tab and activates", () => {
let layout = withTabs(1, 2, 3);
layout = placeTab(layout, 0, 1, { preview: false, activate: true }).layout;
layout = placeTab(layout, 0, 4, { preview: false, activate: true }).layout;
expect(ids(layout)).toEqual([1, 4, 2, 3]);
expect(activeBuffer(layout)).toBe(4);
});
it("replaces the one preview tab in place and reports it", () => {
let layout = withTabs(1, 2);
layout = placeTab(layout, 0, 1, { preview: false, activate: true }).layout;
let result = placeTab(layout, 0, 5, { preview: true, activate: true });
expect(result.replaced).toBeNull();
layout = placeTab(result.layout, 0, 2, { preview: false, activate: true }).layout;
result = placeTab(layout, 0, 6, { preview: true, activate: true });
expect(result.replaced).toBe(5);
expect(ids(result.layout)).toEqual([1, 6, 2]);
expect(result.layout.groups[0]?.tabs.filter((t) => t.preview).map((t) => t.id)).toEqual([6]);
});
it("opening a preview for good, or keeping it open, makes it permanent", () => {
let layout = placeTab(emptyLayout(), 0, 1, { preview: true, activate: true }).layout;
expect(placeTab(layout, 0, 1, { preview: true, activate: true }).layout.groups[0]?.tabs[0]?.preview).toBe(true);
expect(placeTab(layout, 0, 1, { preview: false, activate: true }).layout.groups[0]?.tabs[0]?.preview).toBe(false);
layout = keepOpen(layout, 1);
expect(placeTab(layout, 0, 2, { preview: true, activate: true }).replaced).toBeNull();
});
it("never puts an unpinned tab before a pinned one", () => {
let layout = withTabs(1, 2);
layout = setPinned(layout, 0, 2, true);
expect(ids(layout)).toEqual([2, 1]);
layout = placeTab(layout, 0, 3, { preview: false, activate: true, index: 0 }).layout;
expect(ids(layout)).toEqual([2, 3, 1]);
});
it("leaves the input layout alone", () => {
const layout = withTabs(1);
placeTab(layout, 0, 2, { preview: false, activate: true });
expect(ids(layout)).toEqual([1]);
});
});
describe("pinning", () => {
it("moves a pinned tab to the end of the pinned block and back", () => {
let layout = withTabs(1, 2, 3);
layout = setPinned(layout, 0, 3, true);
layout = setPinned(layout, 0, 2, true);
expect(ids(layout)).toEqual([3, 2, 1]);
layout = setPinned(layout, 0, 3, false);
expect(ids(layout)).toEqual([2, 3, 1]);
});
it("keeps a pinned preview open", () => {
const layout = setPinned(placeTab(emptyLayout(), 0, 1, { preview: true, activate: true }).layout, 0, 1, true);
expect(layout.groups[0]?.tabs[0]).toEqual({ id: 1, pinned: true, preview: false });
});
});
describe("close targets", () => {
const layout = setPinned(withTabs(1, 2, 3, 4, 5), 0, 1, true);
const group = layout.groups[0];
const dirty = (id: number): boolean => id === 4;
it("leave pinned tabs out of every bulk close", () => {
expect(group && closeTargets(group, 3, "others", dirty)).toEqual([2, 4, 5]);
expect(group && closeTargets(group, 3, "all", dirty)).toEqual([2, 3, 4, 5]);
expect(group && closeTargets(group, 3, "left", dirty)).toEqual([2]);
expect(group && closeTargets(group, 3, "right", dirty)).toEqual([4, 5]);
expect(group && closeTargets(group, null, "unmodified", dirty)).toEqual([2, 3, 5]);
});
it("close nothing left or right of a tab the group lacks", () => {
expect(group && closeTargets(group, 99, "left", dirty)).toEqual([]);
expect(group && closeTargets(group, 99, "right", dirty)).toEqual([]);
});
});
describe("removing tabs", () => {
it("activates the right neighbour, else the left one", () => {
let layout = withTabs(1, 2, 3);
layout = placeTab(layout, 0, 2, { preview: false, activate: true }).layout;
layout = removeTab(layout, 0, 2);
expect(activeBuffer(layout)).toBe(3);
layout = removeTab(layout, 0, 3);
expect(activeBuffer(layout)).toBe(1);
layout = removeTab(layout, 0, 1);
expect(activeBuffer(layout)).toBeNull();
expect(layout.groups).toHaveLength(1);
});
});
describe("groups", () => {
it("split shows the active tab in a new focused group, at most two groups", () => {
let layout = split(withTabs(1, 2), "right");
expect(layout.groups).toHaveLength(2);
expect(layout.focused).toBe(1);
expect(ids(layout, 1)).toEqual([2]);
expect(groupsOf(layout, 2)).toEqual([0, 1]);
layout = placeTab(layout, 1, 3, { preview: false, activate: true }).layout;
layout = split(layout, "down");
expect(layout.groups).toHaveLength(2);
expect(layout.orientation).toBe("down");
expect(layout.focused).toBe(0);
expect(ids(layout, 0)).toEqual([1, 2, 3]);
});
it("an emptied group goes away and the focus stays valid", () => {
let layout = split(withTabs(1, 2), "right");
layout = removeTab(layout, 1, 2);
expect(layout.groups).toHaveLength(1);
expect(layout.focused).toBe(0);
expect(ids(layout)).toEqual([1, 2]);
});
it("closing a buffer removes it from both groups", () => {
const layout = removeBuffer(split(withTabs(1, 2), "right"), 2);
expect(layout.groups).toHaveLength(1);
expect(ids(layout)).toEqual([1]);
});
it("moving a tab splits when needed and takes it out of its group", () => {
let layout = moveToOtherGroup(withTabs(1, 2), 0, 2);
expect(ids(layout, 0)).toEqual([1]);
expect(ids(layout, 1)).toEqual([2]);
expect(layout.focused).toBe(1);
layout = moveToOtherGroup(layout, 1, 2);
expect(layout.groups).toHaveLength(1);
expect(ids(layout)).toEqual([1, 2]);
expect(moveToOtherGroup(withTabs(1), 0, 1)).toEqual(withTabs(1));
});
it("unsplit joins the other group's tabs into the focused one", () => {
let layout = split(withTabs(1, 2), "right");
layout = placeTab(layout, 1, 3, { preview: true, activate: true }).layout;
layout = unsplit(layout);
expect(layout.groups).toHaveLength(1);
expect(ids(layout)).toEqual([2, 3, 1]);
expect(layout.groups[0]?.tabs.map((t) => t.preview)).toEqual([false, true, false]);
});
});
describe("stored layout", () => {
it("round-trips groups, pins, previews and the active tabs by path", () => {
let layout = split(setPinned(withTabs(1, 2), 0, 2, true), "down");
layout = placeTab(layout, 1, 3, { preview: true, activate: true }).layout;
const paths: Record<number, string> = { 1: "a.php", 2: "b.php", 3: "c.php" };
const stored = toStored(layout, (id) => paths[id]);
expect(stored).toEqual({
version: 1,
focused: 1,
orientation: "down",
groups: [
{ tabs: [{ path: "b.php", pinned: true, preview: false }, { path: "a.php", pinned: false, preview: false }], active: "b.php" },
{ tabs: [{ path: "b.php", pinned: false, preview: false }, { path: "c.php", pinned: false, preview: true }], active: "c.php" },
],
});
expect(parseStored(JSON.parse(JSON.stringify(stored)))).toEqual(stored);
});
it("reads untrusted values defensively", () => {
for (const bad of [null, 1, "x", [], {}, { version: 2, groups: [] }, { version: 1, groups: "x" }]) {
expect(parseStored(bad)).toBeNull();
}
const parsed = parseStored({
version: 1,
focused: 7,
orientation: "diagonal",
groups: [
{ tabs: [{ path: "a" }, { path: "a" }, { path: "" }, 3, null, { path: "p", pinned: true, preview: true }], active: "nope" },
null,
{ tabs: [] },
{ tabs: [{ path: "c" }] },
],
});
expect(parsed).toEqual({
version: 1,
focused: 0,
orientation: "right",
groups: [{ tabs: [{ path: "p", pinned: true, preview: false }, { path: "a", pinned: false, preview: false }], active: "p" }],
});
});
it("caps the number of stored tabs", () => {
const tabs = Array.from({ length: 500 }, (_, i) => ({ path: `f${String(i)}.php` }));
expect(parseStored({ version: 1, groups: [{ tabs }] })?.groups[0]?.tabs).toHaveLength(200);
});
});
describe("reopen stack", () => {
/**
* A closed tab entry.
*
* @param path - its path.
*/
function entry(path: string): ClosedTab {
return { path, group: 0, index: 0, pinned: false, anchor: 0, head: 0, top: null };
}
it("keeps one entry per path, newest last, and caps its size", () => {
let stack = pushClosed([], entry("a"));
stack = pushClosed(stack, entry("b"));
stack = pushClosed(stack, entry("a"));
expect(stack.map((e) => e.path)).toEqual(["b", "a"]);
for (let i = 0; i < 50; i++) {
stack = pushClosed(stack, entry(String(i)));
}
expect(stack).toHaveLength(MAX_CLOSED);
expect(stack[stack.length - 1]?.path).toBe("49");
});
});

View file

@ -0,0 +1,573 @@
/**
* Tests for tab management in the editor area (C10 A1): preview tabs from
* the project tree and their setting, pinning, bulk closes with one
* question for every unsaved file, the context menu, reopening a closed
* tab with its selection, splitting with one shared buffer, the stored
* layout per project and the public API for other areas. The engine is a
* fake behind the mocked Tauri `invoke`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { EditorView, runScopeHandlers } from "@codemirror/view";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
const invoke = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
import { useCommandsStore } from "../../src/commands/store";
import EditorArea from "../../src/components/editor/EditorArea.vue";
import { emitEditorEvent } from "../../src/components/editor/engineEvents";
import { emitEngineEvent } from "../../src/components/project/engineEvents";
import ProjectToolWindow from "../../src/components/project/ProjectToolWindow.vue";
import { COMMAND_IDS } from "../../src/components/editor/tabs/commands";
import { PREVIEW_SETTING, useEditorStore } from "../../src/stores/editor";
import { useSettingsStore } from "../../src/stores/settings";
/** A buffer of the fake engine. */
interface FakeBuffer {
path: string;
text: string;
version: number;
saved: number;
}
/** Fake engine state. */
let buffers: Map<number, FakeBuffer>;
/** Files on the fake disk. */
let disk: Record<string, string>;
/** Next buffer id. */
let nextId: number;
/** Every `engine_execute` call, in order. */
let calls: { command: string; params: Record<string, unknown> }[];
/** What `layout.get` returns. */
let storedLayout: unknown;
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components to unmount after each test. */
let mounted: VueWrapper[] = [];
/**
* Describes a buffer as `file.open` and `buffer.get` do.
*
* @param id - buffer id.
*/
function describeBuffer(id: number): unknown {
const b = buffers.get(id);
return b ? { id, path: b.path, text: b.text, version: b.version, dirty: b.version !== b.saved, lineEnding: "lf" } : null;
}
/**
* Rejects like the shell does with an engine error.
*
* @param code - error code.
*/
function fail(code: string): Promise<never> {
return Promise.reject(Object.assign(new Error(code), { code, message: code }));
}
/**
* The fake engine's command handler.
*
* @param command - command id.
* @param p - params.
*/
function execute(command: string, p: Record<string, unknown>): Promise<unknown> {
const id = typeof p.id === "number" ? p.id : -1;
const b = buffers.get(id);
switch (command) {
case "file.open": {
const path = String(p.path);
for (const [existing, buffer] of buffers) {
if (buffer.path === path) {
return Promise.resolve(describeBuffer(existing));
}
}
const text = disk[path];
if (text === undefined) {
return fail("not_found");
}
const newId = nextId++;
buffers.set(newId, { path, text, version: 1, saved: 1 });
return Promise.resolve(describeBuffer(newId));
}
case "buffer.get":
return b ? Promise.resolve(describeBuffer(id)) : fail("failed");
case "buffer.edit": {
if (!b) {
return fail("failed");
}
let out = "";
let pos = 0;
for (const e of p.edits as { from: number; to: number; insert: string }[]) {
out += b.text.slice(pos, e.from) + e.insert;
pos = e.to;
}
const wasDirty = b.version !== b.saved;
b.text = out + b.text.slice(pos);
b.version += 1;
if (!wasDirty) {
emitEditorEvent({ kind: "dirtyChanged", id, dirty: true });
}
return Promise.resolve({ id, version: b.version, dirty: true });
}
case "file.save":
if (!b) {
return fail("failed");
}
disk[b.path] = b.text;
b.saved = b.version;
emitEditorEvent({ kind: "dirtyChanged", id, dirty: false });
return Promise.resolve({ id, version: b.version });
case "buffer.close":
if (!b) {
return fail("failed");
}
if (b.version !== b.saved && p.force !== true) {
return fail("unsaved_changes");
}
buffers.delete(id);
emitEditorEvent({ kind: "bufferClosed", id });
return Promise.resolve(null);
case "layout.get":
return Promise.resolve({ layout: storedLayout });
case "layout.set":
return Promise.resolve({ stored: true });
case "project.children":
return Promise.resolve({
dir: "",
entries: Object.keys(disk).map((path) => ({ name: path, path, kind: "file", ignored: false, role: "normal" })),
truncated: false,
});
default:
return Promise.resolve(null);
}
}
/**
* jsdom has no layout; CodeMirror measures text ranges, so give ranges
* empty rectangles.
*/
function stubRangeGeometry(): void {
const empty = (): DOMRectList => Object.assign([] as DOMRect[], { item: () => null });
Range.prototype.getClientRects = empty;
Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0);
}
/** Fresh Pinia and a fake engine with four files on its disk. */
function resetFakeEngine(): void {
stubRangeGeometry();
pinia = createPinia();
setActivePinia(pinia);
buffers = new Map();
disk = { "a.php": "<?php\necho 1;\n", "b.php": "<?php\necho 2;\n", "c.php": "<?php\necho 3;\n", "d.php": "<?php\n" };
nextId = 1;
calls = [];
storedLayout = null;
invoke.mockReset();
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([]);
}
if (cmd === "engine_execute" && args) {
calls.push({ command: args.command, params: args.params });
return execute(args.command, args.params);
}
return Promise.reject(new Error(`unexpected ${cmd}`));
});
}
beforeEach(resetFakeEngine);
afterEach(async () => {
await flushPromises();
useCommandsStore(pinia).stop();
for (const wrapper of mounted) {
wrapper.unmount();
}
mounted = [];
vi.useRealTimers();
});
/** Mounts the editor area and starts the command store. */
async function mountArea(): Promise<VueWrapper> {
await useCommandsStore(pinia).start();
const wrapper = mount(EditorArea, { attachTo: document.body, slots: { default: "empty" }, global: { plugins: [pinia] } });
mounted.push(wrapper);
await flushPromises();
return wrapper;
}
/** Mounts the project tree with the fake project open. */
async function mountTree(): Promise<VueWrapper> {
const tree = mount(ProjectToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(tree);
emitEngineEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" });
await flushPromises();
return tree;
}
/**
* Names on the tab bar of a group, `*` marking previews and `^` pins.
*
* @param area - the mounted area.
* @param group - group index.
*/
function tabNames(area: VueWrapper, group = 0): string[] {
return area.findAll(`[data-test=editor-tabs][data-group='${String(group)}'] [data-test=editor-tab]`).map((tab) => {
const name = tab.find(".tabs__name").text();
return `${tab.attributes("data-pinned") ? "^" : ""}${name}${tab.attributes("data-preview") ? "*" : ""}`;
});
}
/**
* The CodeMirror view of a group.
*
* @param area - the mounted area.
* @param group - group index.
*/
function viewOf(area: VueWrapper, group = 0): EditorView {
const el = area.find(`[data-test=code-editor][data-group='${String(group)}'] .cm-editor`).element;
const view = EditorView.findFromDOM(el as HTMLElement);
if (!view) {
throw new Error("no editor view");
}
return view;
}
/**
* Opens files permanently, in order.
*
* @param paths - project-relative paths.
*/
async function openAll(...paths: string[]): Promise<void> {
const editor = useEditorStore(pinia);
for (const path of paths) {
await editor.openFile(path);
}
await flushPromises();
}
/**
* Makes a buffer dirty through its view.
*
* @param area - the mounted area.
* @param path - file to edit (activated first).
*/
async function makeDirty(area: VueWrapper, path: string): Promise<void> {
const editor = useEditorStore(pinia);
await editor.openFile(path);
await flushPromises();
viewOf(area).dispatch({ changes: { from: 0, insert: "x" } });
await flushPromises();
}
/**
* Mounts the area and the tree once and opens a file, so the cold start of
* the first CodeMirror view and the first render (seconds under load) is
* not paid inside the first test's time budget (see `EditorArea.test.ts`).
*/
beforeAll(async () => {
resetFakeEngine();
const area = await mountArea();
const tree = await mountTree();
await tree.find("[data-path='a.php']").trigger("dblclick");
await flushPromises();
expect(area.find(".cm-editor").exists()).toBe(true);
useCommandsStore(pinia).stop();
for (const wrapper of mounted) {
wrapper.unmount();
}
mounted = [];
}, 30_000);
describe("preview tabs", () => {
it("a single click opens a preview that the next one replaces; a double click keeps it", async () => {
const area = await mountArea();
const tree = await mountTree();
await tree.find("[data-path='a.php']").trigger("click");
await flushPromises();
expect(tabNames(area)).toEqual(["a.php*"]);
expect(area.find("[data-test=editor-tab] .tabs__name").element.closest(".tabs__tab--preview")).not.toBeNull();
await tree.find("[data-path='b.php']").trigger("click");
await flushPromises();
expect(tabNames(area)).toEqual(["b.php*"]);
expect(calls.filter((c) => c.command === "buffer.close").map((c) => c.params)).toEqual([{ id: 1, force: false }]);
await tree.find("[data-path='b.php']").trigger("dblclick");
await flushPromises();
await tree.find("[data-path='c.php']").trigger("click");
await flushPromises();
expect(tabNames(area)).toEqual(["b.php", "c.php*"]);
await area.findAll("[data-test=editor-tab]")[1]?.trigger("dblclick");
expect(tabNames(area)).toEqual(["b.php", "c.php"]);
});
it("editing a preview keeps it open", async () => {
const area = await mountArea();
const editor = useEditorStore(pinia);
await editor.openFile("a.php", { preview: true });
await flushPromises();
viewOf(area).dispatch({ changes: { from: 0, insert: "x" } });
await flushPromises();
await editor.openFile("b.php", { preview: true });
await flushPromises();
expect(tabNames(area)).toEqual(["a.php", "b.php*"]);
});
it("the setting turns previews off", async () => {
const area = await mountArea();
useSettingsStore(pinia).values[PREVIEW_SETTING] = false;
const editor = useEditorStore(pinia);
await editor.openFile("a.php", { preview: true });
await editor.openFile("b.php", { preview: true });
await flushPromises();
expect(tabNames(area)).toEqual(["a.php", "b.php"]);
});
});
describe("pinning and closing", () => {
it("pinned tabs sit left with a pin and survive close others and close all", async () => {
const area = await mountArea();
await openAll("a.php", "b.php", "c.php");
const commands = useCommandsStore(pinia);
await commands.execute(COMMAND_IDS.togglePin, { id: 3 });
await flushPromises();
expect(tabNames(area)).toEqual(["^c.php", "a.php", "b.php"]);
expect(area.findAll("[data-test=tab-pin]")).toHaveLength(1);
await commands.execute(COMMAND_IDS.closeOthers, { id: 1 });
await flushPromises();
expect(tabNames(area)).toEqual(["^c.php", "a.php"]);
await commands.execute(COMMAND_IDS.closeAll);
await flushPromises();
expect(tabNames(area)).toEqual(["^c.php"]);
});
it("closes to the left, to the right and the unmodified tabs", async () => {
const area = await mountArea();
await openAll("a.php", "b.php", "c.php", "d.php");
const editor = useEditorStore(pinia);
await editor.closeAction("right", 3);
await flushPromises();
expect(tabNames(area)).toEqual(["a.php", "b.php", "c.php"]);
await editor.closeAction("left", 2);
await flushPromises();
expect(tabNames(area)).toEqual(["b.php", "c.php"]);
await makeDirty(area, "c.php");
await editor.closeAction("unmodified");
await flushPromises();
expect(tabNames(area)).toEqual(["c.php"]);
});
it("asks once for every unsaved file and saves them all", async () => {
const area = await mountArea();
await openAll("a.php", "b.php", "c.php");
await makeDirty(area, "a.php");
await makeDirty(area, "b.php");
const editor = useEditorStore(pinia);
await editor.closeAction("all");
await flushPromises();
expect(editor.closePrompt?.items.map((i) => i.name)).toEqual(["a.php", "b.php"]);
expect(area.findAll("[data-test=close-list] li").map((li) => li.text())).toEqual(["a.php", "b.php"]);
expect(area.get("[data-test=close-save]").text()).toBe("Save All");
await area.get("[data-test=close-cancel]").trigger("click");
await flushPromises();
expect(tabNames(area)).toEqual(["a.php", "b.php", "c.php"]);
await editor.closeAction("all");
await flushPromises();
await area.get("[data-test=close-save]").trigger("click");
await flushPromises();
expect(tabNames(area)).toEqual([]);
expect(disk["a.php"]?.startsWith("x")).toBe(true);
expect(disk["b.php"]?.startsWith("x")).toBe(true);
});
it("discards every unsaved file with Don't Save", async () => {
const area = await mountArea();
await openAll("a.php", "b.php");
await makeDirty(area, "a.php");
const editor = useEditorStore(pinia);
await editor.closeAction("all");
await flushPromises();
expect(area.find("[data-test=close-list]").exists()).toBe(false);
await area.get("[data-test=close-discard]").trigger("click");
await flushPromises();
expect(tabNames(area)).toEqual([]);
expect(disk["a.php"]).toBe("<?php\necho 1;\n");
expect(calls.filter((c) => c.command === "buffer.close").map((c) => c.params.force)).toEqual([true, true]);
});
it("the context menu runs the tab commands for its tab", async () => {
const area = await mountArea();
await openAll("a.php", "b.php", "c.php");
await area.findAll("[data-test=editor-tab]")[1]?.trigger("contextmenu", { clientX: 10, clientY: 10 });
const items = area.findAll("[data-test=tab-menu-item]").map((i) => i.attributes("data-item"));
expect(items).toEqual([
"close",
COMMAND_IDS.closeOthers,
COMMAND_IDS.closeAll,
COMMAND_IDS.closeLeft,
COMMAND_IDS.closeRight,
COMMAND_IDS.closeUnmodified,
COMMAND_IDS.reopenClosed,
"pin",
COMMAND_IDS.splitRight,
COMMAND_IDS.splitDown,
COMMAND_IDS.moveToOtherGroup,
]);
await area.get(`[data-item='${COMMAND_IDS.closeOthers}']`).trigger("click");
await flushPromises();
expect(tabNames(area)).toEqual(["b.php"]);
expect(area.find("[data-test=tab-menu]").exists()).toBe(false);
});
});
describe("tab context menu and local history", () => {
it("shows Show Local History only while history.show exists and runs it with the path", async () => {
const area = await mountArea();
await openAll("a.php");
await area.get("[data-test=editor-tab]").trigger("contextmenu", { clientX: 5, clientY: 5 });
expect(area.find("[data-item='history.show']").exists()).toBe(false);
await area.get("[data-test=tab-menu]").trigger("keydown", { key: "Escape" });
const shown: unknown[] = [];
useCommandsStore(pinia).provide("history.show", { run: (params) => void shown.push(params) });
await area.get("[data-test=editor-tab]").trigger("contextmenu", { clientX: 5, clientY: 5 });
await area.get("[data-item='history.show']").trigger("click");
await flushPromises();
expect(shown).toEqual([{ path: "a.php" }]);
});
});
describe("reopen closed tab", () => {
it("reopens the last closed tab at its place with its selection", async () => {
const area = await mountArea();
await openAll("a.php", "b.php", "c.php");
const editor = useEditorStore(pinia);
editor.activate(2);
await flushPromises();
viewOf(area).dispatch({ selection: { anchor: 3, head: 7 } });
expect(editor.canReopen).toBe(false);
await editor.requestClose(2);
await flushPromises();
expect(tabNames(area)).toEqual(["a.php", "c.php"]);
await useCommandsStore(pinia).execute(COMMAND_IDS.reopenClosed);
await flushPromises();
expect(tabNames(area)).toEqual(["a.php", "b.php", "c.php"]);
const selection = viewOf(area).state.selection.main;
expect([selection.anchor, selection.head]).toEqual([3, 7]);
expect(editor.canReopen).toBe(false);
});
});
describe("split", () => {
it("shows the same buffer in two groups with one text and one undo history", async () => {
const area = await mountArea();
await openAll("a.php", "b.php");
const editor = useEditorStore(pinia);
await useCommandsStore(pinia).execute(COMMAND_IDS.splitRight);
await flushPromises();
expect(area.findAll("[data-test=editor-pane]")).toHaveLength(2);
expect(tabNames(area, 0)).toEqual(["a.php", "b.php"]);
expect(tabNames(area, 1)).toEqual(["b.php"]);
expect(editor.focusedGroup).toBe(1);
viewOf(area, 1).dispatch({ changes: { from: 0, insert: "// " } });
await flushPromises();
expect(viewOf(area, 0).state.doc.toString()).toBe("// <?php\necho 2;\n");
runScopeHandlers(viewOf(area, 0), new KeyboardEvent("keydown", { key: "z", ctrlKey: true, metaKey: navigator.platform.startsWith("Mac") }), "editor");
await flushPromises();
expect(viewOf(area, 1).state.doc.toString()).toBe("<?php\necho 2;\n");
expect(buffers.get(2)?.text).toBe("<?php\necho 2;\n");
});
it("moves a tab across, focuses the other group and joins the groups again", async () => {
const area = await mountArea();
await openAll("a.php", "b.php", "c.php");
const editor = useEditorStore(pinia);
const commands = useCommandsStore(pinia);
await commands.execute(COMMAND_IDS.moveToOtherGroup, { id: 1 });
await flushPromises();
expect(tabNames(area, 0)).toEqual(["b.php", "c.php"]);
expect(tabNames(area, 1)).toEqual(["a.php"]);
await commands.execute(COMMAND_IDS.focusOtherGroup);
expect(editor.focusedGroup).toBe(0);
await commands.execute(COMMAND_IDS.splitDown);
await flushPromises();
expect(area.find(".editor-area__groups--down").exists()).toBe(true);
await commands.execute(COMMAND_IDS.unsplit);
await flushPromises();
expect(area.findAll("[data-test=editor-pane]")).toHaveLength(1);
});
it("closing a tab the other group still shows keeps the buffer", async () => {
const area = await mountArea();
await openAll("a.php");
const editor = useEditorStore(pinia);
editor.split("right");
await flushPromises();
await makeDirty(area, "a.php");
await editor.requestClose(1, 1);
await flushPromises();
expect(editor.closePrompt).toBeNull();
expect(calls.some((c) => c.command === "buffer.close")).toBe(false);
expect(area.findAll("[data-test=editor-pane]")).toHaveLength(1);
});
});
describe("stored layout", () => {
it("stores changes through layout.set and restores the layout when the project opens", async () => {
storedLayout = {
version: 1,
focused: 1,
orientation: "down",
groups: [
{ tabs: [{ path: "b.php", pinned: true }, { path: "gone.php" }, { path: "a.php" }], active: "a.php" },
{ tabs: [{ path: "c.php", preview: true }], active: "c.php" },
],
};
const area = await mountArea();
emitEditorEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" });
await flushPromises();
await flushPromises();
expect(tabNames(area, 0)).toEqual(["^b.php", "a.php"]);
expect(tabNames(area, 1)).toEqual(["c.php*"]);
expect(area.find(".editor-area__groups--down").exists()).toBe(true);
const editor = useEditorStore(pinia);
expect(editor.focusedGroup).toBe(1);
expect(editor.groups[0]?.activeId).toBe(editor.tabOfPath("a.php")?.id);
expect(calls.some((c) => c.command === "layout.set")).toBe(false);
vi.useFakeTimers();
editor.unsplit();
await vi.advanceTimersByTimeAsync(400);
const set = calls.filter((c) => c.command === "layout.set");
expect(set).toHaveLength(1);
expect((set[0]?.params.layout as { groups: unknown[] }).groups).toHaveLength(1);
});
it("does not store the empty layout of a closing project", async () => {
await mountArea();
emitEditorEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" });
await flushPromises();
await openAll("a.php");
vi.useFakeTimers();
emitEditorEvent({ kind: "projectClosed" });
await vi.advanceTimersByTimeAsync(400);
expect(calls.filter((c) => c.command === "layout.set")).toHaveLength(0);
});
});
describe("public API", () => {
it("finds the tab of a path and reloads a buffer from the engine", async () => {
const area = await mountArea();
await openAll("a.php");
const editor = useEditorStore(pinia);
expect(editor.tabOfPath("a.php")?.id).toBe(1);
expect(editor.tabOfPath("nope.php")).toBeUndefined();
const buffer = buffers.get(1);
if (buffer) {
buffer.text = "reloaded\n";
buffer.version += 1;
}
expect(editor.reloadBuffer(1)).toBe(true);
await flushPromises();
expect(viewOf(area).state.doc.toString()).toBe("reloaded\n");
expect(editor.reloadBuffer(99)).toBe(false);
});
});

View file

@ -340,6 +340,7 @@ describe("find.open prefill", () => {
const find = useFindStore();
const editor = (await import("../../src/stores/editor")).useEditorStore();
const state = EditorState.create({ doc: "echo productName;", selection: EditorSelection.single(8) });
editor.tabs = [{ id: 1, path: "a.php", name: "a.php", dirty: false, notice: null }];
editor.activeId = 1;
vi.spyOn(editor, "syncOf").mockReturnValue({ state } as unknown as ReturnType<typeof editor.syncOf>);
find.query = "(";
@ -440,14 +441,14 @@ describe("Find tool window", () => {
await list.trigger("keydown", { key: "ArrowDown" });
await list.trigger("keydown", { key: "Enter" });
await flushPromises();
expect(reveals).toEqual([{ path: "a.php", line: 4, column: 4 }]);
expect(reveals).toEqual([{ path: "a.php", line: 4, column: 4, preview: true }]);
await list.trigger("keydown", { key: "End" });
expect(wrapper.findAll("[data-test=find-row]")[2]?.attributes("aria-selected")).toBe("true");
await wrapper.findAll("[data-test=find-row]")[0]?.trigger("click");
await flushPromises();
expect(reveals).toEqual([
{ path: "a.php", line: 4, column: 4 },
{ path: "a.php", line: 0, column: 2 },
{ path: "a.php", line: 4, column: 4, preview: true },
{ path: "a.php", line: 0, column: 2, preview: true },
]);
});

View file

@ -329,7 +329,7 @@ describe("keyboard and opening", () => {
await press({ key: "ArrowDown" });
await press({ key: "Enter" });
expect(wrapper.find("[data-test=goto]").exists()).toBe(false);
expect(revealed).toEqual([{ path: "vendor/acme/User.php" }]);
expect(revealed).toEqual([{ path: "vendor/acme/User.php", preview: true }]);
expect(document.activeElement?.id).toBe("host-button");
expect(useModalsStore(pinia).current).toBe(null);
});
@ -346,7 +346,7 @@ describe("keyboard and opening", () => {
expect(rows(wrapper)).toEqual(["find | App\\User"]);
expect(wrapper.findAll("mark").map((m) => m.text())).toEqual(["fi"]);
await wrapper.find("[data-test=goto-row]").trigger("click");
expect(revealed).toEqual([{ path: "src/User.php", line: 7, column: 20 }]);
expect(revealed).toEqual([{ path: "src/User.php", line: 7, column: 20, preview: true }]);
});
it("switches modes with Tab and keeps the text", async () => {

View file

@ -254,7 +254,7 @@ describe("AppMenu", () => {
expect(menuShown()).toBe(true);
expect(menu.find("[data-test=menu-button]").attributes("aria-expanded")).toBe("true");
const headings = [...document.querySelectorAll("[data-test=menu-group]")].map((g) => g.querySelector(".app-menu__heading")?.textContent.trim());
expect(headings).toEqual(["File", "Edit", "View", "Go", "Git", "Tools", "Help"]);
expect(headings).toEqual(["File", "Edit", "View", "Go", "Git", "Tools", "Window", "Help"]);
const listed = listing() as { id: string; menuPath: string | null }[];
const withPath = listed.filter((c) => c.menuPath !== null);
expect([...itemIds()].sort()).toEqual(withPath.map((c) => c.id).sort());

View file

@ -87,7 +87,7 @@ const SHOP = [
*/
function openTab(id: number, path: string): void {
const editor = useEditorStore(pinia);
editor.tabs.push({ id, path, name: path, dirty: false, notice: null });
editor.tabs = [...editor.tabs, { id, path, name: path, dirty: false, notice: null }];
editor.activeId = id;
}