A1: tab management: preview tabs, pinning, close actions, reopen closed tab, split into two groups
- 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:
parent
02922eb89d
commit
7f309dbc4e
28 changed files with 3003 additions and 211 deletions
|
|
@ -150,6 +150,17 @@ export const useCommandsStore = defineStore("commands", () => {
|
|||
return info !== undefined && info.ui !== true && info.enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a command exists: the engine lists it, it is a UI command, or a
|
||||
* component supplies a handler. Menus hide items of commands another
|
||||
* area adds later.
|
||||
*
|
||||
* @param id - the command id.
|
||||
*/
|
||||
function isKnown(id: string): boolean {
|
||||
return handlers.has(id) || all.value.some((c) => c.id === id);
|
||||
}
|
||||
|
||||
/**
|
||||
* The commands the palette offers: UI commands and engine commands that
|
||||
* are user actions (they have a menu path or a default shortcut), not
|
||||
|
|
@ -330,5 +341,5 @@ export const useCommandsStore = defineStore("commands", () => {
|
|||
unsubscribe = null;
|
||||
}
|
||||
|
||||
return { infos, recent, keymap, entries, isEnabled, provide, execute, dispatch, refresh, start, stop };
|
||||
return { infos, recent, keymap, entries, isEnabled, isKnown, provide, execute, dispatch, refresh, start, stop };
|
||||
});
|
||||
|
|
|
|||
|
|
@ -7,6 +7,8 @@
|
|||
* is disabled.
|
||||
*/
|
||||
|
||||
import { TAB_UI_COMMANDS } from "../components/editor/tabs/commands";
|
||||
|
||||
/** A UI command as registered with the engine. */
|
||||
export interface UiCommandSpec {
|
||||
/** Command id, `area.action` in camelCase. */
|
||||
|
|
@ -71,4 +73,5 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
|
|||
{ id: "view.toggleStructure", labelKey: "command.view.toggleStructure", menuPath: "View/Structure", defaultShortcut: "Mod+2" },
|
||||
{ id: "view.selectTheme", labelKey: "command.view.selectTheme", menuPath: "View/Select Theme…" },
|
||||
{ id: "view.importTheme", labelKey: "command.view.importTheme", menuPath: "View/Import Theme…" },
|
||||
...TAB_UI_COMMANDS,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
111
ui/src/components/editor/EditorPane.vue
Normal file
111
ui/src/components/editor/EditorPane.vue
Normal 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>
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
265
ui/src/components/editor/tabs/TabContextMenu.vue
Normal file
265
ui/src/components/editor/tabs/TabContextMenu.vue
Normal 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>
|
||||
137
ui/src/components/editor/tabs/commands.ts
Normal file
137
ui/src/components/editor/tabs/commands.ts
Normal 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));
|
||||
}
|
||||
587
ui/src/components/editor/tabs/model.ts
Normal file
587
ui/src/components/editor/tabs/model.ts
Normal 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);
|
||||
}
|
||||
|
|
@ -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. */
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 });
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -26,6 +26,19 @@
|
|||
"command.palette.open": "Command Palette",
|
||||
"command.problems.open": "Problems",
|
||||
"command.settings.open": "Settings…",
|
||||
"command.tabs.closeAll": "Close All Tabs",
|
||||
"command.tabs.closeLeft": "Close Tabs to the Left",
|
||||
"command.tabs.closeOthers": "Close Other Tabs",
|
||||
"command.tabs.closeRight": "Close Tabs to the Right",
|
||||
"command.tabs.closeUnmodified": "Close Unmodified Tabs",
|
||||
"command.tabs.focusOtherGroup": "Focus Other Group",
|
||||
"command.tabs.keepOpen": "Keep Tab Open",
|
||||
"command.tabs.moveToOtherGroup": "Move Tab to Other Group",
|
||||
"command.tabs.reopenClosed": "Reopen Closed Tab",
|
||||
"command.tabs.splitDown": "Split Down",
|
||||
"command.tabs.splitRight": "Split Right",
|
||||
"command.tabs.togglePin": "Pin or Unpin Tab",
|
||||
"command.tabs.unsplit": "Unsplit",
|
||||
"command.terminal.open": "Terminal",
|
||||
"command.unavailable": "{command} cannot run right now",
|
||||
"command.vcs.abortMerge": "Abort Merge…",
|
||||
|
|
@ -62,6 +75,7 @@
|
|||
"common.dontSave": "Don't Save",
|
||||
"common.error.unexpectedResult": "unexpected result of {command}",
|
||||
"common.save": "Save",
|
||||
"common.saveAll": "Save All",
|
||||
"common.toolWindow.bottomTabs": "Bottom tool windows",
|
||||
"common.toolWindow.collapse": "Collapse {title}",
|
||||
"common.toolWindow.expand": "Expand {title}",
|
||||
|
|
@ -212,6 +226,7 @@
|
|||
"editor.chunk.unstage": "Unstage",
|
||||
"editor.chunk.unstaged": "Not staged",
|
||||
"editor.closePrompt.question": "Save changes to {name} before closing?",
|
||||
"editor.closePrompt.questionMany": "Save changes to these {count} files before closing?",
|
||||
"editor.gitGutter.added": "Added since the staged version",
|
||||
"editor.gitGutter.deleted": "Lines deleted here since the staged version",
|
||||
"editor.gitGutter.modified": "Changed since the staged version",
|
||||
|
|
@ -222,7 +237,14 @@
|
|||
"editor.reveal.openFailed": "could not open {path}",
|
||||
"editor.saveFailed": "save failed",
|
||||
"editor.tabs.close": "Close {name}",
|
||||
"editor.tabs.group": "Editor group {n}",
|
||||
"editor.tabs.label": "Editor tabs",
|
||||
"editor.tabs.menu.close": "Close",
|
||||
"editor.tabs.menu.label": "Actions for {name}",
|
||||
"editor.tabs.menu.pin": "Pin Tab",
|
||||
"editor.tabs.menu.showHistory": "Show Local History",
|
||||
"editor.tabs.menu.unpin": "Unpin Tab",
|
||||
"editor.tabs.pinned": "pinned",
|
||||
"editor.tabs.unsaved": "unsaved changes",
|
||||
"find.action.search": "Search",
|
||||
"find.count.files.one": "1 file",
|
||||
|
|
@ -266,6 +288,7 @@
|
|||
"menu.group.go": "Go",
|
||||
"menu.group.help": "Help",
|
||||
"menu.group.view": "View",
|
||||
"menu.group.window": "Window",
|
||||
"menu.label": "Main menu",
|
||||
"nav.definition.none": "No definition found for {name}",
|
||||
"nav.picker.line": "line {line}",
|
||||
|
|
@ -432,6 +455,8 @@
|
|||
"settings.editor.hover.delayMs.label": "Documentation tooltip delay (ms)",
|
||||
"settings.editor.lineHeight.description": "Height of each editor line relative to the font size. 150 means one and a half times the font size.",
|
||||
"settings.editor.lineHeight.label": "Editor line height (%)",
|
||||
"settings.editor.tabs.preview.description": "A single click in the project tree, search results or Go to opens a preview tab that the next one replaces. Editing it or a double click keeps it open.",
|
||||
"settings.editor.tabs.preview.label": "Preview tabs",
|
||||
"settings.error.browseFailed": "The file picker could not open: {message}",
|
||||
"settings.error.int": "Enter a whole number",
|
||||
"settings.error.intRange": "Enter a whole number from {min} to {max}",
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -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");
|
||||
|
|
|
|||
262
ui/tests/editor/tabModel.test.ts
Normal file
262
ui/tests/editor/tabModel.test.ts
Normal 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");
|
||||
});
|
||||
});
|
||||
573
ui/tests/editor/tabs.test.ts
Normal file
573
ui/tests/editor/tabs.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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 },
|
||||
]);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -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 () => {
|
||||
|
|
|
|||
|
|
@ -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());
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue