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

@ -1,7 +1,8 @@
<script setup lang="ts">
/**
* The question shown when a tab with unsaved changes closes: Save,
* Don't Save or Cancel. Escape cancels; Save has the focus.
* The question shown when tabs with unsaved changes close: Save, Don't
* Save or Cancel, asked once for every such tab of a bulk close (C10 A1),
* which lists the files. Escape cancels; Save has the focus.
*/
import { nextTick, ref, watch } from "vue";
import { t } from "../../i18n";
@ -53,8 +54,24 @@ function onKeydown(event: KeyboardEvent): void {
id="lt-close-prompt-title"
class="close-prompt__text"
>
{{ t("editor.closePrompt.question", { name: editor.closePrompt.name }) }}
{{
editor.closePrompt.items.length === 1
? t("editor.closePrompt.question", { name: editor.closePrompt.items[0]?.name ?? "" })
: t("editor.closePrompt.questionMany", { count: editor.closePrompt.items.length })
}}
</p>
<ul
v-if="editor.closePrompt.items.length > 1"
class="close-prompt__list"
data-test="close-list"
>
<li
v-for="item in editor.closePrompt.items"
:key="item.id"
>
{{ item.name }}
</li>
</ul>
<div class="close-prompt__buttons">
<button
ref="saveButton"
@ -63,7 +80,7 @@ function onKeydown(event: KeyboardEvent): void {
data-test="close-save"
@click="editor.resolveClose('save')"
>
{{ t("common.save") }}
{{ editor.closePrompt.items.length > 1 ? t("common.saveAll") : t("common.save") }}
</button>
<button
type="button"
@ -111,6 +128,13 @@ function onKeydown(event: KeyboardEvent): void {
margin: 0 0 16px;
}
.close-prompt__list {
margin: -8px 0 16px;
padding-left: 20px;
max-height: 200px;
overflow-y: auto;
}
.close-prompt__buttons {
display: flex;
justify-content: flex-end;

View file

@ -1,17 +1,27 @@
<script setup lang="ts">
/**
* The CodeMirror view of the active tab.
* The CodeMirror view of one editor group's active tab.
*
* One view serves every tab: switching tabs swaps in the tab's editor state
* (kept by its {@link BufferSync}), so undo history, selection and scroll
* anchor survive. Every transaction goes through the sync, which forwards
* local edits to the engine.
* One view serves every tab of the group: switching tabs swaps in the
* tab's editor state (kept by its {@link BufferSync}), so undo history,
* selection and scroll anchor survive. Every transaction goes through the
* sync, which forwards local edits to the engine and updates the other
* group's view when it shows the same buffer. The view registers with the
* editor store under its group index; a press in it focuses the group.
*/
import { EditorView } from "@codemirror/view";
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import type { BufferSync } from "./bufferSync";
import { useEditorStore } from "../../stores/editor";
const props = withDefaults(
defineProps<{
/** Index of the editor group the view belongs to. */
group?: number;
}>(),
{ group: 0 },
);
const editor = useEditorStore();
/** Element the view is mounted in. */
@ -21,13 +31,19 @@ let view: EditorView | null = null;
/** Sync of the buffer shown, null if none. */
let attached: BufferSync | null = null;
/** Buffer id of the group's active tab. */
const shownId = computed(() => editor.groups[props.group]?.activeId ?? null);
/**
* Shows a buffer in the view.
*
* @param id - buffer id, or null for none.
* @param focus - move the keyboard focus into the view.
*/
function show(id: number | null): void {
attached?.detach();
function show(id: number | null, focus: boolean): void {
if (view) {
attached?.detach(view);
}
attached = null;
const sync = id === null ? undefined : editor.syncOf(id);
if (!view || !sync || id === null) {
@ -35,12 +51,21 @@ function show(id: number | null): void {
}
attached = sync;
sync.attach(view);
view.focus();
if (focus) {
view.focus();
}
requestAnimationFrame(() => {
editor.markShown(id);
});
}
/** Focuses this group when the view gets a pointer press. */
function onPointerDown(): void {
if (editor.focusedGroup !== props.group) {
editor.focusGroup(props.group);
}
}
onMounted(() => {
if (!host.value) {
return;
@ -55,19 +80,30 @@ onMounted(() => {
}
},
});
show(editor.activeId);
editor.registerView(props.group, view);
show(shownId.value, editor.focusedGroup === props.group);
});
watch(shownId, (id) => {
show(id, editor.focusedGroup === props.group);
});
watch(
() => editor.activeId,
(id) => {
show(id);
() => props.group,
(group, old) => {
editor.registerView(old, null);
if (view) {
editor.registerView(group, view);
}
},
);
onBeforeUnmount(() => {
attached?.detach();
if (view) {
attached?.detach(view);
}
attached = null;
editor.registerView(props.group, null);
view?.destroy();
view = null;
});
@ -78,7 +114,9 @@ onBeforeUnmount(() => {
ref="host"
class="code-editor"
data-test="code-editor"
:data-buffer="editor.activeId ?? undefined"
:data-buffer="shownId ?? undefined"
:data-group="group"
@pointerdown.capture="onPointerDown"
/>
</template>

View file

@ -1,31 +1,30 @@
<script setup lang="ts">
/**
* The editor area: tab bar, a notice line for the active tab, the editor
* and the close question. Without open tabs it shows the default slot.
* The editor area: one or two editor groups side by side or stacked
* (`EditorPane.vue`, C10 A1), the close question and the last editor
* error. Without open tabs it shows the default slot.
*
* Save, save all and close run through the global keymap and the
* palette (`commands/store.ts`): the area supplies their behaviour with the
* active buffer as context and says when they can run. It also supplies the
* UI commands `editor.reveal` (`reveal.ts`) and the assist commands
* (`assist/commands.ts`). Diff tabs (M4.3, `vcs/diff/`) share the tab bar;
* while one is active the diff view replaces the editor, and the area
* supplies the diff commands.
* (`assist/commands.ts`) and the tab management commands
* (`tabs/commands.ts`). Diff tabs (M4.3, `vcs/diff/`) share the first
* group's tab bar; while one is active the diff view replaces that group's
* editor, and the area supplies the diff commands.
*/
import { defineAsyncComponent, onBeforeUnmount, onMounted } from "vue";
import { onBeforeUnmount, onMounted } from "vue";
import { useCommandsStore } from "../../commands/store";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
import ClosePrompt from "./ClosePrompt.vue";
import CodeEditor from "./CodeEditor.vue";
import EditorTabs from "./EditorTabs.vue";
import EditorPane from "./EditorPane.vue";
import { provideTabCommands } from "./tabs/commands";
import { reveal, REVEAL_COMMAND } from "./reveal";
import * as assist from "./assist/commands";
import { provideDiffCommands } from "../vcs/diff/commands";
import { useDiffStore } from "../vcs/diff/diff";
/** The diff view, loaded on first use so `@codemirror/merge` stays out of the start bundle. */
const DiffView = defineAsyncComponent(() => import("../vcs/diff/DiffView.vue"));
const editor = useEditorStore();
const commands = useCommandsStore();
const diff = useDiffStore();
@ -45,6 +44,7 @@ onMounted(() => {
commands.provide(assist.QUICK_DOC_COMMAND, { run: assist.quickDocumentation, enabled: assist.assistEnabled }),
commands.provide(assist.PARAMETER_INFO_COMMAND, { run: assist.parameterInfo, enabled: assist.assistEnabled }),
...provideDiffCommands(commands),
...provideTabCommands(commands, editor),
];
});
@ -62,28 +62,18 @@ onBeforeUnmount(() => {
class="editor-area"
data-test="editor-area"
>
<template v-if="editor.tabs.length > 0 || diff.tabs.length > 0">
<EditorTabs />
<div
v-if="!diff.visible && editor.activeTab?.notice"
class="editor-area__notice"
:class="{ 'editor-area__notice--error': editor.activeTab.notice.kind === 'error' }"
role="status"
data-test="editor-notice"
>
<span>{{ editor.activeTab.notice.message }}</span>
<button
type="button"
class="editor-area__dismiss"
data-test="notice-dismiss"
@click="editor.dismissNotice(editor.activeTab.id)"
>
{{ t("common.dismiss") }}
</button>
</div>
<DiffView v-if="diff.visible" />
<CodeEditor v-else-if="editor.activeTab" />
</template>
<div
v-if="editor.tabs.length > 0 || diff.tabs.length > 0"
class="editor-area__groups"
:class="{ 'editor-area__groups--down': editor.orientation === 'down' }"
data-test="editor-groups"
>
<EditorPane
v-for="group in editor.groups"
:key="group.index"
:group="group.index"
/>
</div>
<div
v-else
class="editor-area__empty"
@ -120,6 +110,26 @@ onBeforeUnmount(() => {
min-height: 0;
}
.editor-area__groups {
display: flex;
flex: 1;
min-width: 0;
min-height: 0;
}
.editor-area__groups > * + * {
border-left: 1px solid var(--lt-border);
}
.editor-area__groups--down {
flex-direction: column;
}
.editor-area__groups--down > * + * {
border-left: none;
border-top: 1px solid var(--lt-border);
}
.editor-area__empty {
flex: 1;
display: flex;

View file

@ -0,0 +1,111 @@
<script setup lang="ts">
/**
* One editor group (C10 A1): its tab bar, the notice line of its active
* tab and its editor. The first group also hosts the diff tabs; while a
* diff is active there, the diff view replaces that group's editor.
*
* Banners about the active tab (C10 A2's conflict banner) belong in this
* pane, between the tab bar and the editor, keyed by
* {@link activeTab}.
*/
import { computed, defineAsyncComponent } from "vue";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
import { useDiffStore } from "../vcs/diff/diff";
import CodeEditor from "./CodeEditor.vue";
import EditorTabs from "./EditorTabs.vue";
/** The diff view, loaded on first use so `@codemirror/merge` stays out of the start bundle. */
const DiffView = defineAsyncComponent(() => import("../vcs/diff/DiffView.vue"));
const props = defineProps<{
/** Index of the editor group. */
group: number;
}>();
const editor = useEditorStore();
const diff = useDiffStore();
/** The group's active tab, null if none. */
const activeTab = computed(() => {
const id = editor.groups[props.group]?.activeId ?? null;
return id === null ? null : (editor.tabOf(id) ?? null);
});
/** Whether the diff view replaces this group's editor. */
const showsDiff = computed(() => props.group === 0 && diff.visible);
</script>
<template>
<div
class="editor-pane"
:class="{ 'editor-pane--focused': editor.groups.length > 1 && editor.focusedGroup === group }"
:aria-label="editor.groups.length > 1 ? t('editor.tabs.group', { n: group + 1 }) : undefined"
:data-group="group"
data-test="editor-pane"
>
<EditorTabs :group="group" />
<div
v-if="!showsDiff && activeTab?.notice"
class="editor-pane__notice"
:class="{ 'editor-pane__notice--error': activeTab.notice.kind === 'error' }"
role="status"
data-test="editor-notice"
>
<span>{{ activeTab.notice.message }}</span>
<button
type="button"
class="editor-pane__dismiss"
data-test="notice-dismiss"
@click="editor.dismissNotice(activeTab.id)"
>
{{ t("common.dismiss") }}
</button>
</div>
<DiffView v-if="showsDiff" />
<CodeEditor
v-else-if="activeTab"
:group="group"
/>
</div>
</template>
<style scoped>
.editor-pane {
display: flex;
flex-direction: column;
flex: 1 1 0;
min-width: 0;
min-height: 0;
border-top: 2px solid transparent;
}
.editor-pane--focused {
border-top-color: var(--lt-accent);
}
.editor-pane__notice {
display: flex;
align-items: center;
gap: 12px;
padding: 4px 12px;
flex-shrink: 0;
color: var(--lt-fg);
background: var(--lt-notice-bg);
border-bottom: 1px solid var(--lt-border);
}
.editor-pane__notice--error {
background: color-mix(in srgb, var(--lt-error) 15%, var(--lt-bg));
}
.editor-pane__dismiss {
margin-left: auto;
padding: 0 8px;
font: inherit;
color: var(--lt-fg);
background: transparent;
border: 1px solid var(--lt-border);
border-radius: 3px;
}
</style>

View file

@ -1,32 +1,54 @@
<script setup lang="ts">
/**
* The tab bar of the editor area, following the WAI-ARIA tabs pattern.
* The tab bar of one editor group, following the WAI-ARIA tabs pattern.
*
* A click activates a tab, a middle click or the close button closes it,
* Left/Right move between tabs. A dot marks unsaved changes. Closing a
* dirty tab asks first (see the editor store). Names are coloured by their
* Git status (`--lt-vcs-*`, M4.4). Diff tabs (M4.3, `vcs/diff/diff.ts`)
* follow the editor tabs; while one is active, no editor tab is marked
* active.
* A click activates a tab, a double click keeps a preview tab open, a
* middle click or the close button closes it, the right button opens the
* tab's context menu (`tabs/TabContextMenu.vue`, C10 A1), Left/Right move
* between tabs. A preview tab has an italic title, a pinned one a pin
* icon. A dot marks unsaved changes. Closing a dirty
* tab asks first (see the editor store). Names are coloured by their Git
* status (`--lt-vcs-*`, M4.4). Diff tabs (M4.3, `vcs/diff/diff.ts`)
* follow the editor tabs of the first group; while one is active, no
* editor tab of that group is marked active.
*/
import { X } from "@lucide/vue";
import { Pin, X } from "@lucide/vue";
import { computed, ref } from "vue";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
import { useVcsStatusStore } from "../../stores/vcsStatus";
import { SHORT_HASH } from "../vcs/changes/changes";
import { useDiffStore, type DiffTab } from "../vcs/diff/diff";
import TabContextMenu from "./tabs/TabContextMenu.vue";
const props = withDefaults(
defineProps<{
/** Index of the editor group. */
group?: number;
}>(),
{ group: 0 },
);
const editor = useEditorStore();
const vcs = useVcsStatusStore();
const diff = useDiffStore();
/** The group's tabs. */
const groupTabs = computed(() => editor.groups[props.group]?.tabs ?? []);
/** Whether this bar shows the diff tabs. */
const showsDiffs = computed(() => props.group === 0);
/** The open context menu, null if none. */
const menu = ref<{ id: number; name: string; x: number; y: number } | null>(null);
/**
* Whether an editor tab is the active one.
* Whether an editor tab is the active one of this group.
*
* @param id - buffer id of the tab.
*/
function isActive(id: number): boolean {
return id === editor.activeId && !diff.visible;
return id === editor.groups[props.group]?.activeId && !(showsDiffs.value && diff.visible);
}
/**
@ -35,8 +57,21 @@ function isActive(id: number): boolean {
* @param id - buffer id of the tab.
*/
function activateTab(id: number): void {
diff.deactivate();
editor.activate(id);
if (showsDiffs.value) {
diff.deactivate();
}
editor.activate(id, props.group);
}
/**
* Opens the context menu of a tab.
*
* @param event - the context menu event.
* @param id - buffer id.
* @param name - file name.
*/
function openMenu(event: MouseEvent, id: number, name: string): void {
menu.value = { id, name, x: event.clientX, y: event.clientY };
}
/**
@ -74,7 +109,7 @@ function onDiffAuxClick(event: MouseEvent, key: string): void {
function onAuxClick(event: MouseEvent, id: number): void {
if (event.button === 1) {
event.preventDefault();
void editor.requestClose(id);
void editor.requestClose(id, props.group);
}
}
@ -84,15 +119,16 @@ function onAuxClick(event: MouseEvent, id: number): void {
* @param event - the key event on the tab list.
*/
function onKeydown(event: KeyboardEvent): void {
const index = editor.tabs.findIndex((t) => t.id === editor.activeId);
const list = groupTabs.value;
const index = list.findIndex((g) => g.tab.id === editor.groups[props.group]?.activeId);
const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;
if (step === 0 || editor.tabs.length === 0) {
if (step === 0 || list.length === 0) {
return;
}
event.preventDefault();
const next = editor.tabs[(index + step + editor.tabs.length) % editor.tabs.length];
const next = list[(index + step + list.length) % list.length];
if (next) {
activateTab(next.id);
activateTab(next.tab.id);
}
}
</script>
@ -102,24 +138,36 @@ function onKeydown(event: KeyboardEvent): void {
class="tabs"
role="tablist"
:aria-label="t('editor.tabs.label')"
:data-group="group"
data-test="editor-tabs"
@keydown="onKeydown"
>
<div
v-for="tab in editor.tabs"
v-for="{ tab, pinned, preview } in groupTabs"
:key="tab.id"
class="tabs__tab"
:class="{ 'tabs__tab--active': isActive(tab.id) }"
:class="{ 'tabs__tab--active': isActive(tab.id), 'tabs__tab--preview': preview, 'tabs__tab--pinned': pinned }"
role="tab"
:tabindex="isActive(tab.id) ? 0 : -1"
:aria-selected="isActive(tab.id)"
:title="tab.path"
:data-id="tab.id"
:data-pinned="pinned || undefined"
:data-preview="preview || undefined"
data-test="editor-tab"
@click="activateTab(tab.id)"
@dblclick="editor.keepOpen(tab.id, group)"
@mousedown.middle.prevent
@auxclick="onAuxClick($event, tab.id)"
@contextmenu.prevent="openMenu($event, tab.id, tab.name)"
>
<Pin
v-if="pinned"
class="tabs__pin"
:size="12"
:aria-label="t('editor.tabs.pinned')"
data-test="tab-pin"
/>
<span
class="tabs__name"
:class="vcs.colourOf(tab.path) ? `tabs__name--vcs-${vcs.colourOf(tab.path)}` : undefined"
@ -137,38 +185,49 @@ function onKeydown(event: KeyboardEvent): void {
tabindex="-1"
:aria-label="t('editor.tabs.close', { name: tab.name })"
data-test="tab-close"
@click.stop="editor.requestClose(tab.id)"
@click.stop="editor.requestClose(tab.id, group)"
>
<X :size="12" />
</button>
</div>
<div
v-for="tab in diff.tabs"
:key="tab.key"
class="tabs__tab"
:class="{ 'tabs__tab--active': tab.key === diff.activeKey }"
role="tab"
:tabindex="tab.key === diff.activeKey ? 0 : -1"
:aria-selected="tab.key === diff.activeKey"
:title="tab.path"
:data-key="tab.key"
data-test="diff-tab"
@click="diff.activate(tab.key)"
@mousedown.middle.prevent
@auxclick="onDiffAuxClick($event, tab.key)"
>
<span class="tabs__name">{{ diffTitle(tab) }}</span>
<button
class="tabs__close"
type="button"
tabindex="-1"
:aria-label="t('vcs.diff.closeTab', { name: tab.name })"
data-test="diff-tab-close"
@click.stop="diff.close(tab.key)"
<template v-if="showsDiffs">
<div
v-for="tab in diff.tabs"
:key="tab.key"
class="tabs__tab"
:class="{ 'tabs__tab--active': tab.key === diff.activeKey }"
role="tab"
:tabindex="tab.key === diff.activeKey ? 0 : -1"
:aria-selected="tab.key === diff.activeKey"
:title="tab.path"
:data-key="tab.key"
data-test="diff-tab"
@click="diff.activate(tab.key)"
@mousedown.middle.prevent
@auxclick="onDiffAuxClick($event, tab.key)"
>
<X :size="12" />
</button>
</div>
<span class="tabs__name">{{ diffTitle(tab) }}</span>
<button
class="tabs__close"
type="button"
tabindex="-1"
:aria-label="t('vcs.diff.closeTab', { name: tab.name })"
data-test="diff-tab-close"
@click.stop="diff.close(tab.key)"
>
<X :size="12" />
</button>
</div>
</template>
<TabContextMenu
v-if="menu"
:id="menu.id"
:group="group"
:name="menu.name"
:x="menu.x"
:y="menu.y"
@close="menu = null"
/>
</div>
</template>
@ -196,6 +255,15 @@ function onKeydown(event: KeyboardEvent): void {
white-space: nowrap;
}
.tabs__tab--preview .tabs__name {
font-style: italic;
}
.tabs__pin {
flex-shrink: 0;
color: var(--lt-fg-muted);
}
.tabs__tab:hover {
color: var(--lt-fg);
}

View file

@ -111,8 +111,12 @@ export class BufferSync {
readonly id: number;
/** The local editor state, always current. */
private current: EditorState;
/** The view showing this buffer, null while another tab is active. */
private view: EditorView | null = null;
/**
* The views showing this buffer: none while another tab is active, two
* when both editor groups show it (they share this one state, so text,
* selection and undo history are the same in both).
*/
private readonly views = new Set<EditorView>();
/** Engine text at {@link version}. */
private confirmed: EngineText;
/** Engine version of {@link confirmed}. */
@ -181,24 +185,40 @@ export class BufferSync {
/**
* Shows this buffer in a view: the view takes over the local state and
* receives remote changes from now on.
* receives every change from now on.
*
* @param view - the editor view.
*/
attach(view: EditorView): void {
this.view = view;
this.views.add(view);
view.setState(this.current);
}
/** Stops updating the view (another tab became active). */
detach(): void {
this.view = null;
/**
* Stops updating a view (another tab became active there).
*
* @param view - the view; every view when omitted.
*/
detach(view?: EditorView): void {
if (view) {
this.views.delete(view);
} else {
this.views.clear();
}
}
/**
* Takes the engine's text over and drops local changes not sent yet, for
* a buffer the engine just reloaded from disk (C10 A2's "Reload").
*/
reload(): void {
this.resync(true);
}
/** Stops syncing; the buffer was closed. */
dispose(): void {
this.disposed = true;
this.view = null;
this.views.clear();
this.inflight = null;
this.unsent = null;
this.settle();
@ -230,7 +250,9 @@ export class BufferSync {
this.unsent = this.unsent ? this.unsent.compose(tr.changes) : tr.changes;
}
}
this.view?.update([...transactions]);
for (const view of this.views) {
view.update([...transactions]);
}
this.flush();
}

View file

@ -8,7 +8,8 @@
* {@link positionOf} (CRLF-safe). Out-of-range values are clamped. Without
* a `path` it centres the cursor of the active tab, which is what running
* it from the palette does. The Find, Go-to and Structure windows and
* agents (`uiCommand`) call it.
* agents (`uiCommand`) call it. With `preview: true` (the Find and Go-to
* windows) a file not open yet opens in a preview tab (C10 A1).
*/
import { EditorView } from "@codemirror/view";
import { nextTick } from "vue";
@ -27,6 +28,8 @@ export interface RevealTarget {
line: number | null;
/** 0-based column in UTF-16 code units. */
column: number;
/** Open a file that has no tab yet as a preview tab. */
preview: boolean;
}
/** The editor store as reveal uses it. */
@ -45,10 +48,11 @@ export function parseReveal(params: unknown): RevealTarget | null {
const path = p.path === undefined || p.path === null ? null : typeof p.path === "string" && p.path !== "" ? p.path : undefined;
const line = number(p.line);
const column = number(p.column);
if (path === undefined || line === undefined || column === undefined) {
const preview = p.preview === undefined || p.preview === null ? false : typeof p.preview === "boolean" ? p.preview : undefined;
if (path === undefined || line === undefined || column === undefined || preview === undefined) {
return null;
}
return { path, line, column: column ?? 0 };
return { path, line, column: column ?? 0, preview };
}
/**
@ -67,11 +71,10 @@ export async function reveal(editor: EditorStore, params: unknown): Promise<void
let id = editor.activeId;
if (target.path !== null) {
const path = target.path;
id = editor.tabs.find((tab) => tab.path === path)?.id ?? (await editor.openFile(path));
id = await editor.openFile(path, { preview: target.preview });
if (id === null) {
throw new Error(editor.lastError?.message ?? t("editor.reveal.openFailed", { path }));
}
editor.activate(id);
await nextTick();
}
const sync = id === null ? undefined : editor.syncOf(id);

View file

@ -0,0 +1,265 @@
<script setup lang="ts">
/**
* The context menu of an editor tab (C10 A1): Close, the bulk closes,
* Reopen Closed Tab, Pin/Unpin, Keep Open (preview tabs), Show Local
* History (`history.show {path}`, C10 A2; hidden while no such command
* exists), the split actions. Every item runs a command of `tabs/commands.ts` (or
* `buffer.close` through the editor store) with the tab as params, so the
* menu, the palette and agents share one behaviour.
*
* Follows the WAI-ARIA menu pattern like the project tree's menu: it takes
* the focus when it opens, Up/Down move (wrapping), Enter or Space runs an
* item, Escape, Tab or a press outside closes it; the position is clamped
* into the window.
*/
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from "vue";
import { useCommandsStore } from "../../../commands/store";
import { t } from "../../../i18n";
import { useEditorStore } from "../../../stores/editor";
import { COMMAND_IDS } from "./commands";
/** Command id of C10 A2's local history for a file. */
const SHOW_HISTORY_COMMAND = "history.show";
const props = defineProps<{
/** Buffer id of the tab. */
id: number;
/** Group index of the tab. */
group: number;
/** File name, for the accessible label. */
name: string;
/** Window x of the pointer in pixels. */
x: number;
/** Window y of the pointer in pixels. */
y: number;
}>();
const emit = defineEmits<{
/** The menu should close (an item ran or the user dismissed it). */
close: [];
}>();
const editor = useEditorStore();
const commands = useCommandsStore();
/** The menu element. */
const menuEl = ref<HTMLElement | null>(null);
/** Index of the focused item. */
const focused = ref(0);
/** One item of the menu. */
interface MenuItem {
/** Stable id, also used by tests. */
id: string;
/** Text shown. */
label: string;
/** Whether it can run now. */
enabled: boolean;
/** Draw a separator above it. */
separated?: boolean;
/** Runs it. */
run: () => Promise<void>;
}
/**
* An item that runs a tab command for this tab.
*
* @param command - command id.
* @param label - text shown.
* @param separated - draw a separator above it.
*/
function commandItem(command: string, label: string, separated = false): MenuItem {
return {
id: command,
label,
enabled: commands.isEnabled(command),
separated,
run: () => commands.execute(command, { id: props.id, group: props.group }),
};
}
/** The items, in order. */
const items = computed<MenuItem[]>(() => {
const pinned = editor.isPinned(props.id, props.group);
const list: MenuItem[] = [
{ id: "close", label: t("editor.tabs.menu.close"), enabled: true, run: () => editor.requestClose(props.id, props.group) },
commandItem(COMMAND_IDS.closeOthers, t("command.tabs.closeOthers")),
commandItem(COMMAND_IDS.closeAll, t("command.tabs.closeAll")),
commandItem(COMMAND_IDS.closeLeft, t("command.tabs.closeLeft")),
commandItem(COMMAND_IDS.closeRight, t("command.tabs.closeRight")),
commandItem(COMMAND_IDS.closeUnmodified, t("command.tabs.closeUnmodified")),
commandItem(COMMAND_IDS.reopenClosed, t("command.tabs.reopenClosed")),
{
...commandItem(COMMAND_IDS.togglePin, pinned ? t("editor.tabs.menu.unpin") : t("editor.tabs.menu.pin"), true),
id: pinned ? "unpin" : "pin",
},
];
if (editor.isPreview(props.id, props.group)) {
list.push(commandItem(COMMAND_IDS.keepOpen, t("command.tabs.keepOpen")));
}
const path = editor.tabOf(props.id)?.path;
if (path !== undefined && commands.isKnown(SHOW_HISTORY_COMMAND)) {
list.push({
id: SHOW_HISTORY_COMMAND,
label: t("editor.tabs.menu.showHistory"),
enabled: commands.isEnabled(SHOW_HISTORY_COMMAND),
separated: true,
run: () => commands.execute(SHOW_HISTORY_COMMAND, { path }),
});
}
list.push(
commandItem(COMMAND_IDS.splitRight, t("command.tabs.splitRight"), true),
commandItem(COMMAND_IDS.splitDown, t("command.tabs.splitDown")),
commandItem(COMMAND_IDS.moveToOtherGroup, t("command.tabs.moveToOtherGroup")),
);
if (editor.groups.length > 1) {
list.push(commandItem(COMMAND_IDS.unsplit, t("command.tabs.unsplit")));
}
return list;
});
/** The menu's position, kept inside the window. */
const position = computed(() => ({
left: `${String(Math.max(0, Math.min(props.x, window.innerWidth - 220)))}px`,
top: `${String(Math.max(0, Math.min(props.y, window.innerHeight - 360)))}px`,
}));
/**
* Runs an item and closes the menu. Split actions act on the active tab,
* so the tab is activated first.
*
* @param item - the item.
*/
async function choose(item: MenuItem): Promise<void> {
if (!item.enabled) {
return;
}
emit("close");
if (item.id === COMMAND_IDS.splitRight || item.id === COMMAND_IDS.splitDown) {
editor.activate(props.id, props.group);
}
await item.run();
}
/**
* Keyboard handling of the menu.
*
* @param event - the key event.
*/
function onKeydown(event: KeyboardEvent): void {
const count = items.value.length;
switch (event.key) {
case "ArrowDown":
focused.value = (focused.value + 1) % count;
break;
case "ArrowUp":
focused.value = (focused.value - 1 + count) % count;
break;
case "Enter":
case " ": {
const item = items.value[focused.value];
if (item) {
void choose(item);
}
break;
}
case "Escape":
case "Tab":
emit("close");
break;
default:
return;
}
event.preventDefault();
event.stopPropagation();
}
/**
* Closes the menu on a press outside it.
*
* @param event - the pointer event on the window.
*/
function onPointerDown(event: PointerEvent): void {
if (menuEl.value && event.target instanceof Node && !menuEl.value.contains(event.target)) {
emit("close");
}
}
onMounted(() => {
window.addEventListener("pointerdown", onPointerDown, true);
void nextTick(() => menuEl.value?.focus());
});
onBeforeUnmount(() => {
window.removeEventListener("pointerdown", onPointerDown, true);
});
</script>
<template>
<div
ref="menuEl"
class="tab-menu"
role="menu"
tabindex="-1"
:aria-label="t('editor.tabs.menu.label', { name })"
:aria-activedescendant="`lt-tab-menu-${items[focused]?.id ?? ''}`"
:style="position"
data-test="tab-menu"
@keydown="onKeydown"
@contextmenu.prevent
>
<div
v-for="(item, index) in items"
:id="`lt-tab-menu-${item.id}`"
:key="item.id"
class="tab-menu__item"
:class="{
'tab-menu__item--focused': index === focused,
'tab-menu__item--disabled': !item.enabled,
'tab-menu__item--separated': item.separated,
}"
role="menuitem"
:aria-disabled="!item.enabled"
:data-item="item.id"
data-test="tab-menu-item"
@mouseenter="focused = index"
@click="choose(item)"
>
{{ item.label }}
</div>
</div>
</template>
<style scoped>
.tab-menu {
position: fixed;
z-index: 50;
min-width: 200px;
padding: 4px 0;
color: var(--lt-fg);
background: var(--lt-bg);
border: 1px solid var(--lt-border);
border-radius: 4px;
outline: none;
}
.tab-menu__item {
padding: 4px 16px;
cursor: default;
white-space: nowrap;
}
.tab-menu__item--separated {
margin-top: 4px;
border-top: 1px solid var(--lt-border);
padding-top: 8px;
}
.tab-menu__item--focused {
background: var(--lt-editor-selection-bg);
}
.tab-menu__item--disabled {
color: var(--lt-fg-muted);
}
</style>

View file

@ -0,0 +1,137 @@
/**
* The tab management UI commands (C10 A1). They are listed in the registry
* through {@link TAB_UI_COMMANDS} (spread into `UI_COMMANDS`), so the
* palette, the Window menu, the keymap editor, agents and the control
* channel reach them. The tab context menu runs the same commands.
*
* Every command takes optional params `{ id?: buffer id, group?: group
* index }`; without them it acts on the active tab of the focused group.
* None has a default shortcut: the obvious keys are taken by Lutra's
* own keymap or by CodeMirror's basicSetup, so users bind them in the
* keymap editor.
*/
import type { CommandHandler, useCommandsStore } from "../../../commands/store";
import type { UiCommandSpec } from "../../../commands/uiCommands";
import type { JsonValue } from "../../../ipc";
import type { useEditorStore } from "../../../stores/editor";
import type { CloseAction } from "./model";
/** Command ids of this module. */
export const COMMAND_IDS = {
closeOthers: "tabs.closeOthers",
closeAll: "tabs.closeAll",
closeLeft: "tabs.closeLeft",
closeRight: "tabs.closeRight",
closeUnmodified: "tabs.closeUnmodified",
reopenClosed: "tabs.reopenClosed",
togglePin: "tabs.togglePin",
keepOpen: "tabs.keepOpen",
splitRight: "tabs.splitRight",
splitDown: "tabs.splitDown",
moveToOtherGroup: "tabs.moveToOtherGroup",
focusOtherGroup: "tabs.focusOtherGroup",
unsplit: "tabs.unsplit",
} as const;
/** Menu path prefix of the tab commands. */
const MENU = "Window/Editor Tabs/";
/** The registry entries of the tab commands. */
export const TAB_UI_COMMANDS: readonly UiCommandSpec[] = [
{ id: COMMAND_IDS.closeOthers, labelKey: "command.tabs.closeOthers", menuPath: `${MENU}Close Other Tabs` },
{ id: COMMAND_IDS.closeAll, labelKey: "command.tabs.closeAll", menuPath: `${MENU}Close All Tabs` },
{ id: COMMAND_IDS.closeLeft, labelKey: "command.tabs.closeLeft", menuPath: `${MENU}Close Tabs to the Left` },
{ id: COMMAND_IDS.closeRight, labelKey: "command.tabs.closeRight", menuPath: `${MENU}Close Tabs to the Right` },
{ id: COMMAND_IDS.closeUnmodified, labelKey: "command.tabs.closeUnmodified", menuPath: `${MENU}Close Unmodified Tabs` },
{ id: COMMAND_IDS.reopenClosed, labelKey: "command.tabs.reopenClosed", menuPath: `${MENU}Reopen Closed Tab` },
{ id: COMMAND_IDS.togglePin, labelKey: "command.tabs.togglePin", menuPath: `${MENU}Pin or Unpin Tab` },
{ id: COMMAND_IDS.keepOpen, labelKey: "command.tabs.keepOpen", menuPath: `${MENU}Keep Tab Open` },
{ id: COMMAND_IDS.splitRight, labelKey: "command.tabs.splitRight", menuPath: "Window/Split Right" },
{ id: COMMAND_IDS.splitDown, labelKey: "command.tabs.splitDown", menuPath: "Window/Split Down" },
{ id: COMMAND_IDS.moveToOtherGroup, labelKey: "command.tabs.moveToOtherGroup", menuPath: "Window/Move Tab to Other Group" },
{ id: COMMAND_IDS.focusOtherGroup, labelKey: "command.tabs.focusOtherGroup", menuPath: "Window/Focus Other Group" },
{ id: COMMAND_IDS.unsplit, labelKey: "command.tabs.unsplit", menuPath: "Window/Unsplit" },
];
/** The tab a command acts on. */
export interface TabTarget {
/** Buffer id; the group's active tab when undefined. */
id?: number | undefined;
/** Group index; the focused group when undefined. */
group?: number | undefined;
}
/**
* Reads `{ id?, group? }` from untrusted params; fields of the wrong type
* are ignored.
*
* @param params - the command params.
*/
export function parseTarget(params: JsonValue): TabTarget {
const p = typeof params === "object" && params !== null && !Array.isArray(params) ? params : {};
const int = (value: JsonValue | undefined): number | undefined =>
typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined;
return { id: int(p.id), group: int(p.group) };
}
/**
* Supplies the behaviour of the tab commands.
*
* @param commands - the command store.
* @param editor - the editor store.
* @returns functions that withdraw the handlers.
*/
export function provideTabCommands(commands: ReturnType<typeof useCommandsStore>, editor: ReturnType<typeof useEditorStore>): (() => void)[] {
const hasTab = (): boolean => editor.activeId !== null;
const split = (): boolean => editor.groups.length > 1;
const close = (action: CloseAction): CommandHandler => ({
run: async (params) => {
const target = parseTarget(params);
await editor.closeAction(action, target.id, target.group);
},
enabled: hasTab,
});
const handlers: [string, CommandHandler][] = [
[COMMAND_IDS.closeOthers, close("others")],
[COMMAND_IDS.closeAll, close("all")],
[COMMAND_IDS.closeLeft, close("left")],
[COMMAND_IDS.closeRight, close("right")],
[COMMAND_IDS.closeUnmodified, close("unmodified")],
[COMMAND_IDS.reopenClosed, { run: async () => { await editor.reopenClosed(); }, enabled: () => editor.canReopen }],
[
COMMAND_IDS.togglePin,
{
run: (params) => {
const target = parseTarget(params);
editor.setPinned(target.id, target.group);
},
enabled: hasTab,
},
],
[
COMMAND_IDS.keepOpen,
{
run: (params) => {
const target = parseTarget(params);
editor.keepOpen(target.id, target.group);
},
enabled: hasTab,
},
],
[COMMAND_IDS.splitRight, { run: () => { editor.split("right"); }, enabled: hasTab }],
[COMMAND_IDS.splitDown, { run: () => { editor.split("down"); }, enabled: hasTab }],
[
COMMAND_IDS.moveToOtherGroup,
{
run: (params) => {
const target = parseTarget(params);
editor.moveToOtherGroup(target.id, target.group);
},
enabled: () => hasTab() && (split() || editor.tabs.length > 1),
},
],
[COMMAND_IDS.focusOtherGroup, { run: () => { editor.focusOtherGroup(); }, enabled: split }],
[COMMAND_IDS.unsplit, { run: () => { editor.unsplit(); }, enabled: split }],
];
return handlers.map(([id, handler]) => commands.provide(id, handler));
}

View file

@ -0,0 +1,587 @@
/**
* The tab layout of the editor area as pure functions (C10 A1): one or two
* editor groups, each with its own row of tabs and active tab.
*
* A tab places an engine buffer in a group. The same buffer may sit in both
* groups; it is still one engine buffer with one undo history (the editor
* store keeps one {@link BufferSync} per buffer). Every function here
* returns a new layout and leaves its input alone, so the store can replace
* its state in one step and tests can check each rule on plain data.
*
* Rules:
* - **Preview:** a group holds at most one preview tab. Opening another
* preview replaces it in place; editing it, opening the same file for
* good or "Keep open" makes it permanent.
* - **Pinned** tabs sit left of the unpinned ones; bulk closes leave them.
* - **Groups:** at most {@link MAX_GROUPS}. A group whose last tab closes
* goes away while another group is left.
*/
/** Most editor groups (v1: one split). */
export const MAX_GROUPS = 2;
/** How two groups sit next to each other. */
export type SplitOrientation = "right" | "down";
/** One tab: a buffer placed in a group. */
export interface TabPlacement {
/** Engine buffer id. */
id: number;
/** Pinned tabs sit left and survive bulk closes. */
pinned: boolean;
/** A preview tab is replaced by the next preview in its group. */
preview: boolean;
}
/** One editor group. */
export interface TabGroup {
/** Tabs in display order, pinned ones first. */
tabs: TabPlacement[];
/** Buffer id of the group's active tab, null when the group is empty. */
activeId: number | null;
}
/** The whole layout of the editor area. */
export interface TabLayout {
/** One or two groups; never empty. */
groups: TabGroup[];
/** Index of the group that has the focus. */
focused: number;
/** Where the second group sits. */
orientation: SplitOrientation;
}
/** How a tab is placed by {@link placeTab}. */
export interface PlaceOptions {
/** Open as a preview tab. */
preview: boolean;
/** Make it the group's active tab and focus the group. */
activate: boolean;
/** Pin it. */
pinned?: boolean | undefined;
/** Index to insert at (clamped to the pinned or unpinned block). */
index?: number | undefined;
}
/** Result of {@link placeTab}. */
export interface PlaceResult {
/** The new layout. */
layout: TabLayout;
/** Buffer id of the preview tab that was replaced, null if none. */
replaced: number | null;
}
/** Bulk close actions of a tab's context menu. */
export type CloseAction = "others" | "all" | "left" | "right" | "unmodified";
/** An empty layout: one group without tabs. */
export function emptyLayout(): TabLayout {
return { groups: [{ tabs: [], activeId: null }], focused: 0, orientation: "right" };
}
/**
* A copy of a layout whose groups and tab rows can be changed freely.
*
* @param layout - the layout to copy.
*/
function copy(layout: TabLayout): TabLayout {
return {
groups: layout.groups.map((g) => ({ activeId: g.activeId, tabs: g.tabs.map((t) => ({ ...t })) })),
focused: layout.focused,
orientation: layout.orientation,
};
}
/**
* The number of pinned tabs at the start of a group.
*
* @param group - the group.
*/
export function pinnedCount(group: TabGroup): number {
return group.tabs.filter((t) => t.pinned).length;
}
/**
* Indexes of the groups that show a buffer.
*
* @param layout - the layout.
* @param id - buffer id.
*/
export function groupsOf(layout: TabLayout, id: number): number[] {
return layout.groups.flatMap((g, index) => (g.tabs.some((t) => t.id === id) ? [index] : []));
}
/**
* Every buffer id in the layout, once, in group then tab order.
*
* @param layout - the layout.
*/
export function bufferIds(layout: TabLayout): number[] {
return [...new Set(layout.groups.flatMap((g) => g.tabs.map((t) => t.id)))];
}
/**
* The active buffer of the focused group, null if it is empty.
*
* @param layout - the layout.
*/
export function activeBuffer(layout: TabLayout): number | null {
return layout.groups[layout.focused]?.activeId ?? null;
}
/**
* A group index clamped to the layout; the focused group when omitted.
*
* @param layout - the layout.
* @param group - wanted index.
*/
export function groupIndex(layout: TabLayout, group?: number | null): number {
if (group === undefined || group === null || !Number.isInteger(group)) {
return layout.focused;
}
return Math.min(Math.max(group, 0), layout.groups.length - 1);
}
/**
* Places a buffer in a group: activates its tab when the group has it,
* replaces the group's preview tab when a preview opens, else inserts a new
* tab after the active one (inside the pinned or unpinned block).
*
* @param layout - the layout.
* @param group - group index (clamped).
* @param id - buffer id.
* @param options - see {@link PlaceOptions}.
* @returns the new layout and the replaced preview's buffer id.
*/
export function placeTab(layout: TabLayout, group: number, id: number, options: PlaceOptions): PlaceResult {
const next = copy(layout);
const index = groupIndex(next, group);
const target = next.groups[index];
if (!target) {
return { layout: next, replaced: null };
}
let replaced: number | null = null;
const existing = target.tabs.find((t) => t.id === id);
if (existing) {
if (!options.preview) {
existing.preview = false;
}
} else {
const pinned = options.pinned === true;
const tab: TabPlacement = { id, pinned, preview: options.preview && !pinned };
const previewAt = tab.preview ? target.tabs.findIndex((t) => t.preview) : -1;
const old = target.tabs[previewAt];
if (old) {
replaced = old.id;
target.tabs.splice(previewAt, 1, tab);
if (target.activeId === old.id) {
target.activeId = id;
}
} else {
const pins = pinnedCount(target);
const activeAt = target.tabs.findIndex((t) => t.id === target.activeId);
const wanted = options.index ?? (activeAt < 0 ? target.tabs.length : activeAt + 1);
const [low, high] = pinned ? [0, pins] : [pins, target.tabs.length];
target.tabs.splice(Math.min(Math.max(wanted, low), high), 0, tab);
}
}
if (options.activate || target.activeId === null) {
target.activeId = id;
}
if (options.activate) {
next.focused = index;
}
return { layout: next, replaced };
}
/**
* Activates a tab and focuses its group.
*
* @param layout - the layout.
* @param group - group index.
* @param id - buffer id; nothing changes when the group lacks it.
*/
export function activateTab(layout: TabLayout, group: number, id: number): TabLayout {
const target = layout.groups[group];
if (!target?.tabs.some((t) => t.id === id)) {
return layout;
}
const next = copy(layout);
const nextGroup = next.groups[group];
if (nextGroup) {
nextGroup.activeId = id;
}
next.focused = group;
return next;
}
/**
* Focuses a group.
*
* @param layout - the layout.
* @param group - group index (clamped).
*/
export function focusGroup(layout: TabLayout, group: number): TabLayout {
const index = groupIndex(layout, group);
return index === layout.focused ? layout : { ...copy(layout), focused: index };
}
/**
* Drops empty groups while more than one is left and keeps
* {@link TabLayout.focused} valid.
*
* @param layout - a layout this module owns (changed in place).
*/
function collapse(layout: TabLayout): TabLayout {
const focusedGroup = layout.groups[layout.focused];
if (layout.groups.length > 1) {
layout.groups = layout.groups.filter((g) => g.tabs.length > 0);
if (layout.groups.length === 0) {
layout.groups = [{ tabs: [], activeId: null }];
}
}
const kept = focusedGroup ? layout.groups.indexOf(focusedGroup) : -1;
layout.focused = kept >= 0 ? kept : Math.min(layout.focused, layout.groups.length - 1);
return layout;
}
/**
* Removes a tab from one group; its right (else left) neighbour becomes the
* group's active tab. An emptied group goes away while another is left.
*
* @param layout - the layout.
* @param group - group index.
* @param id - buffer id.
*/
export function removeTab(layout: TabLayout, group: number, id: number): TabLayout {
const next = copy(layout);
const target = next.groups[group];
const at = target ? target.tabs.findIndex((t) => t.id === id) : -1;
if (!target || at < 0) {
return layout;
}
target.tabs.splice(at, 1);
if (target.activeId === id) {
target.activeId = target.tabs[Math.min(at, target.tabs.length - 1)]?.id ?? null;
}
return collapse(next);
}
/**
* Removes a buffer from every group (the engine closed it).
*
* @param layout - the layout.
* @param id - buffer id.
*/
export function removeBuffer(layout: TabLayout, id: number): TabLayout {
let next = layout;
for (const group of groupsOf(layout, id).reverse()) {
next = removeTab(next, group, id);
}
return next;
}
/**
* Makes every tab of a buffer permanent (it was edited or opened for good).
*
* @param layout - the layout.
* @param id - buffer id.
* @param group - only this group; every group when omitted.
*/
export function keepOpen(layout: TabLayout, id: number, group?: number): TabLayout {
const has = layout.groups.some((g, index) => (group === undefined || index === group) && g.tabs.some((t) => t.id === id && t.preview));
if (!has) {
return layout;
}
const next = copy(layout);
next.groups.forEach((g, index) => {
if (group === undefined || index === group) {
for (const tab of g.tabs) {
if (tab.id === id) {
tab.preview = false;
}
}
}
});
return next;
}
/**
* Pins or unpins a tab. A pinned tab moves to the end of the pinned block,
* an unpinned one to the start of the unpinned block; pinning also keeps a
* preview open.
*
* @param layout - the layout.
* @param group - group index.
* @param id - buffer id.
* @param pinned - the new state.
*/
export function setPinned(layout: TabLayout, group: number, id: number, pinned: boolean): TabLayout {
const next = copy(layout);
const target = next.groups[group];
const at = target ? target.tabs.findIndex((t) => t.id === id) : -1;
const tab = target?.tabs[at];
if (!target || !tab || tab.pinned === pinned) {
return layout;
}
target.tabs.splice(at, 1);
tab.pinned = pinned;
tab.preview = false;
target.tabs.splice(pinnedCount(target), 0, tab);
return next;
}
/**
* The buffers a bulk close removes from a group. Pinned tabs always stay.
*
* @param group - the group.
* @param id - buffer id of the tab the action starts from (ignored by
* `all` and `unmodified`).
* @param action - which tabs to close.
* @param dirty - whether a buffer has unsaved changes (for `unmodified`).
* @returns buffer ids in tab order.
*/
export function closeTargets(group: TabGroup, id: number | null, action: CloseAction, dirty: (id: number) => boolean): number[] {
const at = group.tabs.findIndex((t) => t.id === id);
return group.tabs
.filter((tab, index) => {
if (tab.pinned) {
return false;
}
switch (action) {
case "others":
return tab.id !== id;
case "all":
return true;
case "left":
return at >= 0 && index < at;
case "right":
return at >= 0 && index > at;
case "unmodified":
return !dirty(tab.id);
}
return false;
})
.map((tab) => tab.id);
}
/**
* Splits the editor area: the active tab of the focused group opens in the
* other group too (a new group when there is one), which gets the focus.
* With two groups already, it sets the orientation and shows the tab there.
*
* @param layout - the layout.
* @param orientation - where the other group sits.
*/
export function split(layout: TabLayout, orientation: SplitOrientation): TabLayout {
const id = activeBuffer(layout);
const next = copy(layout);
next.orientation = orientation;
if (next.groups.length < MAX_GROUPS) {
next.groups.push({ tabs: [], activeId: null });
}
const other = otherGroup(next);
if (id === null || other === null) {
return next;
}
return placeTab(next, other, id, { preview: false, activate: true }).layout;
}
/**
* The index of the group that does not have the focus, null with one group.
*
* @param layout - the layout.
*/
export function otherGroup(layout: TabLayout): number | null {
return layout.groups.length < 2 ? null : layout.focused === 0 ? 1 : 0;
}
/**
* Moves a tab to the other group (splitting to the right when there is
* only one group) and focuses it there. A buffer already shown there is
* only activated.
*
* @param layout - the layout.
* @param group - group index of the tab.
* @param id - buffer id.
*/
export function moveToOtherGroup(layout: TabLayout, group: number, id: number): TabLayout {
const source = layout.groups[group];
const tab = source?.tabs.find((t) => t.id === id);
if (!tab) {
return layout;
}
if (layout.groups.length === 1 && source && source.tabs.length === 1) {
return layout;
}
let next = copy(layout);
if (next.groups.length < MAX_GROUPS) {
next.groups.push({ tabs: [], activeId: null });
}
const target = group === 0 ? 1 : 0;
next = placeTab(next, target, id, { preview: tab.preview, activate: true, pinned: tab.pinned }).layout;
const sourceGroup = next.groups[group];
const at = sourceGroup ? sourceGroup.tabs.findIndex((t) => t.id === id) : -1;
if (sourceGroup && at >= 0) {
sourceGroup.tabs.splice(at, 1);
if (sourceGroup.activeId === id) {
sourceGroup.activeId = sourceGroup.tabs[Math.min(at, sourceGroup.tabs.length - 1)]?.id ?? null;
}
}
return collapse(next);
}
/**
* Joins both groups into one: tabs of the other group that the focused one
* lacks are added at its end.
*
* @param layout - the layout.
*/
export function unsplit(layout: TabLayout): TabLayout {
const other = otherGroup(layout);
if (other === null) {
return layout;
}
const next = copy(layout);
const kept = next.groups[next.focused];
const dropped = next.groups[other];
if (!kept || !dropped) {
return layout;
}
for (const tab of dropped.tabs) {
if (!kept.tabs.some((t) => t.id === tab.id)) {
kept.tabs.splice(tab.pinned ? pinnedCount(kept) : kept.tabs.length, 0, { ...tab, preview: false });
}
}
kept.activeId ??= dropped.activeId;
return { groups: [kept], focused: 0, orientation: next.orientation };
}
/** A tab as the layout file stores it (paths instead of buffer ids). */
export type StoredTab = {
/** Project-relative path. */
path: string;
/** Pinned. */
pinned: boolean;
/** Preview. */
preview: boolean;
};
/** A group as the layout file stores it. */
export type StoredGroup = {
/** Tabs in order. */
tabs: StoredTab[];
/** Path of the active tab, null if none. */
active: string | null;
};
/** The layout of a project as Lutra's state file stores it. */
export type StoredLayout = {
/** Format version, {@link STORED_VERSION}. */
version: number;
/** One or two groups. */
groups: StoredGroup[];
/** Focused group. */
focused: number;
/** Where the second group sits. */
orientation: SplitOrientation;
};
/** Version of {@link StoredLayout}. */
export const STORED_VERSION = 1;
/** Most tabs one stored group may hold; more are dropped when reading. */
export const MAX_STORED_TABS = 200;
/**
* Converts a layout for storing.
*
* @param layout - the layout.
* @param pathOf - project-relative path of a buffer, undefined if unknown.
*/
export function toStored(layout: TabLayout, pathOf: (id: number) => string | undefined): StoredLayout {
const groups = layout.groups.map((g) => ({
tabs: g.tabs.flatMap((t) => {
const path = pathOf(t.id);
return path === undefined ? [] : [{ path, pinned: t.pinned, preview: t.preview }];
}),
active: g.activeId === null ? null : (pathOf(g.activeId) ?? null),
}));
return { version: STORED_VERSION, groups, focused: layout.focused, orientation: layout.orientation };
}
/**
* Reads a stored layout from untrusted JSON. Unknown or malformed parts are
* dropped; a value that is not a layout at all gives null.
*
* @param value - what the state file held.
*/
export function parseStored(value: unknown): StoredLayout | null {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
return null;
}
const v = value as Record<string, unknown>;
if (v.version !== STORED_VERSION || !Array.isArray(v.groups)) {
return null;
}
const groups: StoredGroup[] = [];
for (const raw of v.groups.slice(0, MAX_GROUPS)) {
if (typeof raw !== "object" || raw === null) {
continue;
}
const g = raw as Record<string, unknown>;
const tabs: StoredTab[] = [];
const seen = new Set<string>();
for (const rawTab of Array.isArray(g.tabs) ? g.tabs.slice(0, MAX_STORED_TABS) : []) {
if (typeof rawTab !== "object" || rawTab === null) {
continue;
}
const tab = rawTab as Record<string, unknown>;
if (typeof tab.path !== "string" || tab.path === "" || seen.has(tab.path)) {
continue;
}
seen.add(tab.path);
tabs.push({ path: tab.path, pinned: tab.pinned === true, preview: tab.preview === true && tab.pinned !== true });
}
tabs.sort((a, b) => Number(b.pinned) - Number(a.pinned));
const active = typeof g.active === "string" && seen.has(g.active) ? g.active : (tabs[0]?.path ?? null);
if (tabs.length > 0) {
groups.push({ tabs, active });
}
}
const focused = typeof v.focused === "number" && Number.isInteger(v.focused) ? Math.min(Math.max(v.focused, 0), Math.max(groups.length - 1, 0)) : 0;
const orientation: SplitOrientation = v.orientation === "down" ? "down" : "right";
return { version: STORED_VERSION, groups, focused, orientation };
}
/** A closed tab, for "Reopen Closed Tab". */
export interface ClosedTab {
/** Project-relative path. */
path: string;
/** Group it sat in. */
group: number;
/** Index in that group. */
index: number;
/** Whether it was pinned. */
pinned: boolean;
/** Selection anchor, as a CodeMirror position. */
anchor: number;
/** Selection head. */
head: number;
/** Position at the top of the view, null when unknown. */
top: number | null;
}
/** Most entries of the reopen stack. */
export const MAX_CLOSED = 30;
/**
* Pushes a closed tab on the reopen stack; an older entry of the same path
* goes away and the stack keeps at most {@link MAX_CLOSED} entries.
*
* @param stack - the stack, newest last.
* @param entry - the closed tab.
*/
export function pushClosed(stack: readonly ClosedTab[], entry: ClosedTab): ClosedTab[] {
return [...stack.filter((e) => e.path !== entry.path), entry].slice(-MAX_CLOSED);
}

View file

@ -128,7 +128,7 @@ function dirName(path: string): string {
*/
function openRow(row: FindRow): void {
find.select(row.key);
void commands.execute("editor.reveal", { path: row.path, line: row.match.line, column: row.match.column });
void commands.execute("editor.reveal", { path: row.path, line: row.match.line, column: row.match.column, preview: true });
}
/** Starts a search for the fields' current values. */

View file

@ -197,7 +197,9 @@ function choose(item: GotoItem | undefined): void {
}
close();
const params: JsonValue =
item.line === null ? { path: item.path } : { path: item.path, line: item.line, column: item.column ?? 0 };
item.line === null
? { path: item.path, preview: true }
: { path: item.path, line: item.line, column: item.column ?? 0, preview: true };
void commands.execute("editor.reveal", params);
}

View file

@ -2,8 +2,9 @@
* The app menu's model (M3.9): the commands that have a menu path, grouped
* by the path's first segment.
*
* - **Groups** come in Lutra's order (File, Edit, View, Go, Help); a group
* Lutra does not know goes before Help, sorted by name. Empty groups are
* - **Groups** come in Lutra's order (File, Edit, View, Go, then Window and
* Help last); a group Lutra does not know goes before Window, sorted by
* name. Empty groups are
* left out. Known group names come from the catalog.
* - **Items** in a group follow {@link ITEM_ORDER}; others come after it,
* sorted by label.
@ -38,7 +39,7 @@ export interface MenuGroup {
}
/** Known groups in display order. */
const GROUP_ORDER = ["File", "Edit", "View", "Go", "Help"];
const GROUP_ORDER = ["File", "Edit", "View", "Go", "Window", "Help"];
/** Order of known commands inside their group. */
const ITEM_ORDER = [
@ -58,6 +59,19 @@ const ITEM_ORDER = [
"goto.fileOpen",
"goto.classOpen",
"goto.symbolOpen",
"tabs.splitRight",
"tabs.splitDown",
"tabs.moveToOtherGroup",
"tabs.focusOtherGroup",
"tabs.unsplit",
"tabs.closeOthers",
"tabs.closeAll",
"tabs.closeLeft",
"tabs.closeRight",
"tabs.closeUnmodified",
"tabs.reopenClosed",
"tabs.togglePin",
"tabs.keepOpen",
"app.about",
];
@ -76,6 +90,8 @@ function groupLabel(key: string): string {
return t("menu.group.view");
case "Go":
return t("menu.group.go");
case "Window":
return t("menu.group.window");
case "Help":
return t("menu.group.help");
default:
@ -91,7 +107,7 @@ function groupLabel(key: string): string {
function groupRank(key: string): number {
const index = GROUP_ORDER.indexOf(key);
if (index >= 0) {
return key === "Help" ? 1000 : index;
return key === "Help" ? 1000 : key === "Window" ? 900 : index;
}
return 500;
}

View file

@ -5,8 +5,9 @@
*
* Keys: Up/Down move the selection, Home/End jump to the first/last row,
* Right expands a folder or moves into it, Left collapses a folder or moves
* to the parent, Enter opens a file or toggles a folder. Double-click does
* the same as Enter. Ignored and excluded entries are dimmed. A directory
* to the parent, Enter opens a file or toggles a folder. A single click on
* a file opens it in a preview tab (C10 A1); double-click does the same as
* Enter and keeps the tab open. Ignored and excluded entries are dimmed. A directory
* the engine listed only partly ends with a "listing truncated" note.
* File names are coloured by their Git status (`--lt-vcs-*`, M4.4); inside
* a repository, ignored entries take the ignored colour.
@ -177,6 +178,8 @@ function onRowClick(entry: TreeEntry, onChevron: boolean): void {
project.select(entry.path);
if (onChevron && entry.kind === "dir") {
void project.toggle(entry.path);
} else if (entry.kind !== "dir") {
void editor.openFile(entry.path, { preview: true });
}
}