feat(plugins): add settings shortcut entry and drag edge avoidance

This commit is contained in:
ezreal authored and GitHub committed 2026-09-28 21:02:37 +08:00
1 parent fd6b7bd502
commit e444c15e0c
32 files changed
+483 -34

No files matched your search

@@ -252,7 +252,9 @@ async function refresh(preferredPluginId = props.focusTarget?.pluginId || select
try {
[installedPlugins.value, trustedKeys.value, repositories.value] = await Promise.all([api.listPlugins(), api.listPluginTrustedKeys(), api.listPluginRepositories()]);
await refreshMarketplace();
if (props.focusTarget) applyFocusTarget(props.focusTarget);
// Settings navigation is handled immediately by the watcher; replaying it
// after loading would overwrite any subsequent navigation by the user.
if (props.focusTarget && props.focusTarget.section !== "settings") applyFocusTarget(props.focusTarget);
else selectFirstProvider(preferredPluginId);
} catch (cause) {
error.value = cause instanceof Error ? cause.message : String(cause);
@@ -278,6 +280,10 @@ async function refreshMarketplace() {
}
function applyFocusTarget(focus: PluginCenterFocus) {
if (focus.section === "settings") {
activeSection.value = "settings";
return;
}
activeSection.value = "installed";
if (!focus.pluginId) return selectFirstProvider();
const provider = connectionProviders.value.find((entry) => entry.plugin.manifest.id === focus.pluginId && (!focus.providerId || entry.contribution.id === focus.providerId));
@@ -907,9 +913,9 @@ watch(providerConnections, (connections) => {
watch(
() => props.focusTarget,
(focus) => {
if (focus && installedPlugins.value.length) applyFocusTarget(focus);
if (focus && (focus.section === "settings" || installedPlugins.value.length)) applyFocusTarget(focus);
},
{ deep: true },
{ deep: true, immediate: true },
);
let lastHandledInstallRequestId = 0;
watch(
@@ -1,10 +1,11 @@
// @vitest-environment happy-dom
import { createApp, h, nextTick, reactive, ref } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { OPEN_PLUGIN_SETTINGS } from "@/lib/plugins/pluginCenterNavigation";
import PluginShortcutBar from "./PluginShortcutBar.vue";
import { normalizePluginShortcutSettings, type PluginShortcutPosition } from "@/lib/plugins/pluginShortcuts";
const mocks = vi.hoisted(() => ({ open: vi.fn(), save: vi.fn(), toast: vi.fn(), state: null as any, entries: null as any }));
const mocks = vi.hoisted(() => ({ openSettings: vi.fn(), open: vi.fn(), save: vi.fn(), toast: vi.fn(), state: null as any, entries: null as any }));
vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => mocks.state }));
vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
@@ -27,6 +28,7 @@ function mount(position: PluginShortcutPosition) {
container = document.createElement("div");
document.body.append(container);
app = createApp({ render: () => h(PluginShortcutBar, { position }) });
app.provide(OPEN_PLUGIN_SETTINGS, mocks.openSettings);
app.mount(container);
const scroll = container.querySelector("[data-shortcut-scroll]") as HTMLElement;
scroll.getBoundingClientRect = () => box(0, 0, 100, 200);
@@ -41,16 +43,62 @@ function pointer(element: EventTarget, type: string, x: number, y: number) {
}
beforeEach(() => {
vi.clearAllMocks();
mocks.state = reactive({ isEditorSettingsLoaded: true, editorSettings: { pluginShortcuts: normalizePluginShortcutSettings({}) }, updateEditorSettingsAndPersist: mocks.save });
mocks.state = reactive({ isEditorSettingsLoaded: true, editorSettings: { pluginShortcuts: normalizePluginShortcutSettings({ showSettingsEntry: false }) }, updateEditorSettingsAndPersist: mocks.save });
mocks.entries = ref(["a", "b", "c"].map((id) => ({ id, pluginId: id, label: `Function ${id}`, pluginName: `Plugin ${id}`, kind: "workbench", targetId: id, disabled: false })));
mocks.save.mockResolvedValue(undefined);
});
afterEach(() => {
app?.unmount();
container?.remove();
vi.restoreAllMocks();
});
describe("plugin shortcut bar", () => {
it.each(["left-top", "right-top", "sidebar-bottom"] as const)("keeps the measured preview inside both edges at %s", async (position) => {
const original = HTMLElement.prototype.getBoundingClientRect;
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
return this.hasAttribute("data-shortcut-drag-preview") ? box(0, 0, 180, 32) : original.call(this);
});
const items = mount(position);
pointer(items[0], "pointerdown", 16, 16);
pointer(window, "pointermove", window.innerWidth - 2, window.innerHeight - 2);
await flush();
const preview = document.querySelector<HTMLElement>("[data-shortcut-drag-preview]")!;
expect(preview.style.left).toBe(`${window.innerWidth - 194}px`);
expect(preview.style.top).toBe(`${window.innerHeight - 46}px`);
pointer(window, "pointermove", 2, 2);
await flush();
expect(preview.style.left).toBe("14px");
expect(preview.style.top).toBe("14px");
expect(preview.style.visibility).not.toBe("hidden");
});
it.each(["left-top", "left-bottom", "right-top", "right-bottom", "sidebar-bottom"] as const)("keeps settings last and outside sorting at %s", async (position) => {
mocks.state.editorSettings.pluginShortcuts.showSettingsEntry = true;
mount(position);
const button = container.querySelector<HTMLElement>("[data-plugin-shortcut-settings]")!;
const buttons = container.querySelectorAll("button");
if (position === "sidebar-bottom") {
expect(container.querySelector("[data-shortcut-header]")?.contains(button)).toBe(true);
expect(container.querySelector("[data-shortcut-scroll] [data-plugin-shortcut-settings]")).toBeNull();
} else expect(buttons[buttons.length - 1]).toBe(button);
expect(button.closest("[data-shortcut-id]")).toBeNull();
pointer(button, "pointerdown", 16, 120);
pointer(window, "pointermove", 1, 1);
pointer(window, "pointerup", 1, 1);
await flush();
expect(mocks.save).not.toHaveBeenCalled();
expect(document.querySelector(".shortcut-drag-preview")).toBeNull();
button.click();
expect(mocks.openSettings).toHaveBeenCalledOnce();
mocks.entries.value = [];
await flush();
expect(container.querySelector("[data-plugin-shortcut-settings]")).toBeNull();
expect(container.querySelector("nav")).toBeNull();
mocks.state.editorSettings.pluginShortcuts.showSettingsEntry = false;
await flush();
expect(container.querySelector("nav")).toBeNull();
});
it.each(["left-top", "left-bottom", "right-top", "right-bottom", "sidebar-bottom"] as const)("sorts with pointer events at %s without launching on release", async (position) => {
const items = mount(position);
await nextTick();
@@ -62,7 +110,7 @@ describe("plugin shortcut bar", () => {
expect(document.querySelector(".shortcut-drag-preview")).not.toBeNull();
pointer(window, "pointerup", 1, 1);
await flush();
expect(mocks.save).toHaveBeenCalledWith({ pluginShortcuts: { ...normalizePluginShortcutSettings({}), order: ["c", "a", "b"] } });
expect(mocks.save).toHaveBeenCalledWith({ pluginShortcuts: { ...normalizePluginShortcutSettings({ showSettingsEntry: false }), order: ["c", "a", "b"] } });
(items[2].querySelector("button") as HTMLElement).click();
expect(mocks.open).not.toHaveBeenCalled();
expect(document.querySelector(".shortcut-drag-preview")).toBeNull();
@@ -1,5 +1,7 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { computed, inject, ref, watch } from "vue";
import { Settings2 } from "@lucide/vue";
import { OPEN_PLUGIN_SETTINGS } from "@/lib/plugins/pluginCenterNavigation";
import { useI18n } from "vue-i18n";
import { Button } from "@/components/ui/button";
import LightTooltip from "@/components/ui/LightTooltip.vue";
@@ -7,6 +9,7 @@ import PluginIcon from "./PluginIcon.vue";
import { usePluginShortcuts } from "@/composables/usePluginShortcuts";
import { usePluginShortcutPreferences } from "@/composables/usePluginShortcutPreferences";
import { usePluginShortcutSort } from "@/composables/usePluginShortcutSort";
import { useCursorFloatingPosition } from "@/composables/useCursorFloatingPosition";
import { usePluginShortcutHeight } from "@/composables/usePluginShortcutHeight";
import { useSettingsStore } from "@/stores/settingsStore";
import { useToast } from "@/composables/useToast";
@@ -15,6 +18,8 @@ import { movePluginShortcut, type PluginShortcutEntry, type PluginShortcutPositi
const props = defineProps<{ position: PluginShortcutPosition }>();
const { t } = useI18n();
const settings = useSettingsStore();
const openSettings = inject(OPEN_PLUGIN_SETTINGS, () => {});
const showSettingsEntry = computed(() => settings.editorSettings.pluginShortcuts.showSettingsEntry);
const { toast } = useToast();
const { entries, open, isActive } = usePluginShortcuts();
const { update, saving } = usePluginShortcutPreferences();
@@ -56,6 +61,8 @@ const sorting = usePluginShortcutSort({
},
});
const { drag } = sorting;
const preview = ref<HTMLElement | null>(null);
const previewStyle = useCursorFloatingPosition(preview, drag, () => (right.value ? "left" : "right"));
const draggedEntry = computed(() => entries.value.find((entry) => entry.id === drag.source));
watch(() => props.position, sorting.cancel);
function activate(entry: PluginShortcutEntry) {
@@ -66,6 +73,9 @@ function activate(entry: PluginShortcutEntry) {
toast(String(error), 5000);
}
}
function activateSettings() {
if (!sorting.suppressClick()) openSettings();
}
</script>
<template>
@@ -79,7 +89,7 @@ function activate(entry: PluginShortcutEntry) {
@dragstart.prevent
>
<div
v-if="sidebarList"
v-if="sidebarList && entries.length"
data-shortcut-resize
role="separator"
tabindex="0"
@@ -92,7 +102,15 @@ function activate(entry: PluginShortcutEntry) {
@dblclick="!saving && sizing.reset()"
@keydown="!saving && sizing.resizeWithKeyboard($event)"
/>
<div ref="scroll" data-shortcut-scroll class="min-h-0 overflow-y-auto overflow-x-hidden p-1" :class="sidebarList ? 'shrink-0' : 'flex-1'" :style="sidebarList ? { height: `${sizing.height.value}px` } : undefined">
<div v-if="sidebarList" data-shortcut-header class="flex h-8 shrink-0 items-center justify-between gap-2 border-b border-border/60 px-3" :class="{ 'border-t': !entries.length }">
<span class="min-w-0 truncate text-xs font-medium text-muted-foreground">{{ t("pluginPlatform.shortcutsHeading") }}</span>
<LightTooltip v-if="showSettingsEntry" :text="t('pluginPlatform.shortcutsSettings')" :disabled="drag.active || sizing.resizing.value" side="top">
<Button variant="ghost" size="icon" data-plugin-shortcut-settings class="shortcut-button size-6 shrink-0" :aria-label="t('pluginPlatform.shortcutsSettings')" @click="activateSettings">
<Settings2 class="size-3.5 text-foreground" />
</Button>
</LightTooltip>
</div>
<div v-show="!sidebarList || entries.length" ref="scroll" data-shortcut-scroll class="min-h-0 overflow-y-auto overflow-x-hidden p-1" :class="sidebarList ? 'shrink-0' : 'flex-1'" :style="sidebarList ? { height: `${sizing.height.value}px` } : undefined">
<div class="shortcut-items flex flex-col" :class="sidebarList ? 'gap-0' : ['min-h-full gap-1', { 'shortcut-items--bottom': bottom }]">
<LightTooltip v-for="(entry, index) in entries" :key="entry.id" :text="entry.label" :disabled="drag.active || sizing.resizing.value" :side="sidebarList ? 'top' : left ? 'right' : 'left'" content-class="shortcut-tooltip">
<span
@@ -124,14 +142,24 @@ function activate(entry: PluginShortcutEntry) {
</Button>
</span>
</LightTooltip>
<LightTooltip v-if="showSettingsEntry && !sidebarList" :text="t('pluginPlatform.shortcutsSettings')" :disabled="drag.active || sizing.resizing.value" :side="left ? 'right' : 'left'" content-class="shortcut-tooltip">
<span class="relative flex shrink-0" :class="{ 'mt-auto': bottom && !entries.length, 'pt-2': entries.length > 0 }">
<span v-if="entries.length" class="pointer-events-none absolute inset-x-2 top-0 z-10 h-px bg-border/60" aria-hidden="true" />
<Button variant="ghost" size="icon" data-plugin-shortcut-settings class="shortcut-button size-8 shrink-0" :aria-label="t('pluginPlatform.shortcutsSettings')" @click="activateSettings">
<Settings2 class="size-4 shrink-0 text-foreground" />
</Button>
</span>
</LightTooltip>
</div>
</div>
<Teleport to="body">
<div v-if="drag.active || sizing.resizing.value" class="shortcut-pointer-overlay fixed inset-0 select-none touch-none" :style="{ cursor: drag.active ? 'grabbing' : 'row-resize' }" aria-hidden="true" />
<div
v-if="drag.active && draggedEntry"
class="shortcut-drag-preview pointer-events-none fixed flex w-max max-w-xs items-center gap-2 rounded-md border border-primary/50 bg-popover px-2 py-1.5 text-xs text-popover-foreground shadow-md"
:style="{ left: `${drag.x + (right ? -12 : 12)}px`, top: `${drag.y + 12}px`, transform: right ? 'translateX(-100%)' : undefined }"
ref="preview"
data-shortcut-drag-preview
class="shortcut-drag-preview pointer-events-none fixed flex w-max max-w-xs overflow-hidden items-center gap-2 rounded-md border border-primary/50 bg-popover px-2 py-1.5 text-xs text-popover-foreground shadow-md"
:style="previewStyle"
aria-hidden="true"
>
<PluginIcon :plugin-id="draggedEntry.pluginId" :icon="draggedEntry.icon" class="size-4 [&_svg]:text-current" />
@@ -36,6 +36,16 @@ afterEach(() => {
container.remove();
});
describe("plugin shortcut settings", () => {
it("saves the settings shortcut choice without affecting plugin order", async () => {
(container.querySelector("#plugin-shortcuts-settings-entry") as HTMLElement).click();
await vi.waitFor(() => expect(mocks.state.editorSettings.pluginShortcuts.showSettingsEntry).toBe(false));
expect(mocks.state.editorSettings.pluginShortcuts.order).toEqual(["saved"]);
await vi.waitFor(() => expect(container.querySelector("#plugin-shortcuts-settings-entry")?.hasAttribute("disabled")).toBe(false));
mocks.save.mockRejectedValueOnce(new Error("disk full"));
(container.querySelector("#plugin-shortcuts-settings-entry") as HTMLElement).click();
await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalled());
expect(mocks.state.editorSettings.pluginShortcuts.showSettingsEntry).toBe(false);
});
it("selects the Plugin Center dropdown and preserves unrelated preferences", async () => {
const trigger = container.querySelector<HTMLElement>('[role="combobox"]')!;
trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
@@ -48,8 +58,8 @@ describe("plugin shortcut settings", () => {
});
it("shows one toggle per plugin and preserves choices under the global switch", async () => {
const switches = container.querySelectorAll<HTMLElement>('[role="switch"]');
expect(switches).toHaveLength(2);
switches[1].click();
expect(switches).toHaveLength(3);
switches[2].click();
await vi.waitFor(() => expect(mocks.state.editorSettings.pluginShortcuts.hiddenPluginIds).toEqual(["p"]));
await vi.waitFor(() => expect(switches[0].hasAttribute("disabled")).toBe(false));
switches[0].click();
@@ -47,6 +47,10 @@ async function togglePlugin(pluginId: string, visible: boolean) {
<Label for="plugin-shortcuts-enabled" class="text-xs">{{ t("pluginPlatform.shortcutsEnabled") }}</Label>
<Switch id="plugin-shortcuts-enabled" :model-value="settings.editorSettings.pluginShortcuts.enabled" :disabled="saving || !settings.isEditorSettingsLoaded" @update:model-value="update({ enabled: $event })" />
</div>
<div v-if="settings.editorSettings.pluginShortcuts.enabled" class="flex items-center justify-between gap-4">
<Label for="plugin-shortcuts-settings-entry" class="text-xs">{{ t("pluginPlatform.shortcutsShowSettings") }}</Label>
<Switch id="plugin-shortcuts-settings-entry" :model-value="settings.editorSettings.pluginShortcuts.showSettingsEntry" :disabled="saving || !settings.isEditorSettingsLoaded" @update:model-value="update({ showSettingsEntry: $event })" />
</div>
<div v-if="settings.editorSettings.pluginShortcuts.enabled" class="flex items-center justify-between gap-4">
<Label for="plugin-shortcuts-position" class="text-xs">{{ t("pluginPlatform.shortcutsPosition") }}</Label>
<Select :model-value="settings.editorSettings.pluginShortcuts.position" :disabled="saving || !settings.isEditorSettingsLoaded" @update:model-value="update({ position: String($event) as PluginShortcutSettings['position'] })">
@@ -1,10 +1,11 @@
// @vitest-environment happy-dom
import { createApp, h, nextTick, reactive, ref } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { OPEN_PLUGIN_SETTINGS } from "@/lib/plugins/pluginCenterNavigation";
import PluginShortcutToolbar from "./PluginShortcutToolbar.vue";
import { normalizePluginShortcutSettings } from "@/lib/plugins/pluginShortcuts";
const mocks = vi.hoisted(() => ({ open: vi.fn(), save: vi.fn(), toast: vi.fn(), state: null as any, entries: null as any }));
const mocks = vi.hoisted(() => ({ openSettings: vi.fn(), open: vi.fn(), save: vi.fn(), toast: vi.fn(), state: null as any, entries: null as any }));
vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => mocks.state }));
vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
@@ -27,7 +28,7 @@ beforeEach(() => {
vi.clearAllMocks();
width = undefined;
dropdownOnly.value = false;
mocks.state = reactive({ isEditorSettingsLoaded: true, editorSettings: { pluginShortcuts: normalizePluginShortcutSettings({ position: "toolbar", toolbarCount: 2 }) }, updateEditorSettingsAndPersist: mocks.save });
mocks.state = reactive({ isEditorSettingsLoaded: true, editorSettings: { pluginShortcuts: normalizePluginShortcutSettings({ position: "toolbar", toolbarCount: 2, showSettingsEntry: false }) }, updateEditorSettingsAndPersist: mocks.save });
mocks.entries = ref(["a", "b", "c", "d", "e"].map((id) => ({ id, pluginId: id, label: `Function ${id}`, pluginName: `Plugin ${id}`, kind: "workbench", targetId: id, disabled: false })));
mocks.save.mockResolvedValue(undefined);
vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockImplementation(function (this: HTMLElement) {
@@ -47,6 +48,7 @@ beforeEach(() => {
host = document.createElement("div");
document.body.append(host);
app = createApp({ render: () => h(PluginShortcutToolbar, { dropdownOnly: dropdownOnly.value }) });
app.provide(OPEN_PLUGIN_SETTINGS, mocks.openSettings);
app.mount(host);
});
afterEach(() => {
@@ -70,6 +72,76 @@ function pointer(target: EventTarget, type: string, x: number, y: number) {
}
describe("floating plugin shortcuts", () => {
it.each([false, true])("keeps drag previews in the viewport (dropdownOnly=%s)", async (menuOnly) => {
dropdownOnly.value = menuOnly;
if (menuOnly) await openMenu();
else await flush();
const original = HTMLElement.prototype.getBoundingClientRect;
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
return this.hasAttribute("data-shortcut-drag-preview") ? rect(0, 0, 180, 32) : original.call(this);
});
const item = document.querySelector<HTMLElement>("[data-shortcut-id]")!;
pointer(item, "pointerdown", 16, 16);
pointer(window, "pointermove", window.innerWidth - 2, window.innerHeight - 2);
await flush();
const preview = document.querySelector<HTMLElement>("[data-shortcut-drag-preview]")!;
expect(preview.style.left).toBe(`${window.innerWidth - 194}px`);
expect(preview.style.top).toBe(`${window.innerHeight - 46}px`);
pointer(window, "pointermove", 2, 2);
await flush();
expect(preview.style.left).toBe("14px");
expect(preview.style.top).toBe("14px");
});
it.each([false, true])("keeps settings as the last non-sortable menu action (dropdownOnly=%s)", async (menuOnly) => {
dropdownOnly.value = menuOnly;
mocks.state.editorSettings.pluginShortcuts.showSettingsEntry = true;
await openMenu();
const menu = document.querySelector<HTMLElement>("[data-plugin-shortcut-overflow]")!;
const action = menu.querySelector<HTMLElement>("[data-plugin-shortcut-settings]")!;
expect(menu.lastElementChild).toBe(action);
expect(action.hasAttribute("data-shortcut-id")).toBe(false);
pointer(action, "pointerdown", 16, 80);
pointer(window, "pointermove", 1, 1);
pointer(window, "pointerup", 1, 1);
await flush();
expect(mocks.save).not.toHaveBeenCalled();
action.click();
expect(mocks.openSettings).toHaveBeenCalledOnce();
await flush();
expect(document.querySelector("[data-plugin-shortcut-overflow]")).toBeNull();
});
it("reserves room for inline settings and moves it to overflow when the toolbar shrinks", async () => {
mocks.state.editorSettings.pluginShortcuts.showSettingsEntry = true;
mocks.state.editorSettings.pluginShortcuts.toolbarCount = 10;
await flush();
const buttons = host.querySelectorAll("button");
expect(buttons[buttons.length - 1]?.hasAttribute("data-plugin-shortcut-settings")).toBe(true);
width = 34;
resize();
await flush();
expect(host.querySelector("[data-plugin-shortcut-settings]")).toBeNull();
await openMenu();
expect(document.querySelector("[data-plugin-shortcut-overflow]")?.lastElementChild?.hasAttribute("data-plugin-shortcut-settings")).toBe(true);
mocks.state.editorSettings.pluginShortcuts.showSettingsEntry = false;
await flush();
expect(document.querySelector("[data-plugin-shortcut-settings]")).toBeNull();
});
it.each([false, true])("hides the entire area without visible plugins even when settings is enabled (dropdownOnly=%s)", async (menuOnly) => {
dropdownOnly.value = menuOnly;
mocks.state.editorSettings.pluginShortcuts.showSettingsEntry = true;
await openMenu();
const originalEntries = mocks.entries.value;
mocks.entries.value = [];
await flush();
expect(host.querySelector("nav")).toBeNull();
expect(document.querySelector("[data-plugin-shortcut-settings]")).toBeNull();
expect(document.querySelector("[data-plugin-shortcut-overflow]")).toBeNull();
mocks.entries.value = originalEntries;
await flush();
expect(host.querySelector("nav")).not.toBeNull();
expect(document.querySelector("[data-plugin-shortcut-overflow]")).toBeNull();
});
it("shows all shortcuts beside Plugin Center regardless of the floating icon count", async () => {
dropdownOnly.value = true;
mocks.state.editorSettings.pluginShortcuts.toolbarCount = 10;
@@ -1,7 +1,8 @@
<script setup lang="ts">
import { computed, nextTick, onScopeDispose, ref, watch } from "vue";
import { computed, inject, nextTick, onScopeDispose, ref, watch } from "vue";
import { OPEN_PLUGIN_SETTINGS } from "@/lib/plugins/pluginCenterNavigation";
import { useI18n } from "vue-i18n";
import { ChevronDown } from "@lucide/vue";
import { ChevronDown, Settings2 } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import LightTooltip from "@/components/ui/LightTooltip.vue";
@@ -9,6 +10,7 @@ import PluginIcon from "./PluginIcon.vue";
import { usePluginShortcuts } from "@/composables/usePluginShortcuts";
import { usePluginShortcutPreferences } from "@/composables/usePluginShortcutPreferences";
import { usePluginShortcutSort } from "@/composables/usePluginShortcutSort";
import { useCursorFloatingPosition } from "@/composables/useCursorFloatingPosition";
import { useSettingsStore } from "@/stores/settingsStore";
import { useToast } from "@/composables/useToast";
import { movePluginShortcut, pluginShortcutToolbarCount, pluginShortcutToolbarWidth, type PluginShortcutEntry } from "@/lib/plugins/pluginShortcuts";
@@ -17,6 +19,8 @@ const props = defineProps<{ dropdownOnly?: boolean; menuAnchor?: HTMLElement | n
const emit = defineEmits<{ "layout-change": [] }>();
const { t } = useI18n();
const settings = useSettingsStore();
const openSettings = inject(OPEN_PLUGIN_SETTINGS, () => {});
const showSettingsEntry = computed(() => settings.editorSettings.pluginShortcuts.showSettingsEntry);
const { toast } = useToast();
const { entries, open, isActive } = usePluginShortcuts();
const { update, saving } = usePluginShortcutPreferences();
@@ -26,10 +30,11 @@ const moreTrigger = ref<HTMLElement | null>(null);
const menuOpen = ref(false);
const measuredWidth = ref<number | null>(null);
const requested = computed(() => (props.dropdownOnly ? 0 : settings.editorSettings.pluginShortcuts.toolbarCount));
const preferredWidth = computed(() => pluginShortcutToolbarWidth(entries.value.length, requested.value));
const count = computed(() => pluginShortcutToolbarCount(entries.value.length, requested.value, measuredWidth.value ?? preferredWidth.value));
const preferredWidth = computed(() => pluginShortcutToolbarWidth(entries.value.length, requested.value) + (showSettingsEntry.value && entries.value.length <= requested.value ? (entries.value.length ? 30 : 34) : 0));
const count = computed(() => Math.min(entries.value.length, requested.value, pluginShortcutToolbarCount(entries.value.length + Number(showSettingsEntry.value), requested.value + Number(showSettingsEntry.value), measuredWidth.value ?? preferredWidth.value)));
const inlineEntries = computed(() => entries.value.slice(0, count.value));
const overflowEntries = computed(() => entries.value.slice(count.value));
const hasMenu = computed(() => entries.value.length > 0 && (overflowEntries.value.length > 0 || (props.dropdownOnly && showSettingsEntry.value)));
const ids = computed(() => entries.value.map((entry) => entry.id));
const sorting = usePluginShortcutSort({
container: root,
@@ -46,6 +51,8 @@ const sorting = usePluginShortcutSort({
},
});
const { drag } = sorting;
const preview = ref<HTMLElement | null>(null);
const previewStyle = useCursorFloatingPosition(preview, drag);
const draggedEntry = computed(() => entries.value.find((entry) => entry.id === drag.source));
let observer: ResizeObserver | null = null;
let hoverTimer: ReturnType<typeof setTimeout> | null = null;
@@ -70,8 +77,8 @@ watch(
{ flush: "post" },
);
watch(preferredWidth, () => void nextTick(measure));
watch(overflowEntries, (entries) => {
if (!entries.length) menuOpen.value = false;
watch(hasMenu, (visible) => {
if (!visible) menuOpen.value = false;
});
watch(menuOpen, (open) => {
if (!open) sorting.cancel();
@@ -111,6 +118,14 @@ function activate(entry: PluginShortcutEntry, event?: Event) {
toast(String(error), 5000);
}
}
function activateSettings(event?: Event) {
if (sorting.suppressClick()) {
event?.preventDefault();
return;
}
menuOpen.value = false;
openSettings();
}
onScopeDispose(() => {
observer?.disconnect();
clearHoverTimer();
@@ -119,7 +134,7 @@ onScopeDispose(() => {
<template>
<nav
v-if="settings.isEditorSettingsLoaded && entries.length"
v-if="settings.isEditorSettingsLoaded && settings.editorSettings.pluginShortcuts.enabled && entries.length"
ref="root"
data-plugin-shortcut-toolbar
:aria-label="t('pluginPlatform.shortcutsTitle')"
@@ -141,10 +156,16 @@ onScopeDispose(() => {
</Button>
</span>
</LightTooltip>
<DropdownMenu v-if="overflowEntries.length" v-model:open="menuOpen" :modal="false">
<DropdownMenu v-if="hasMenu" v-model:open="menuOpen" :modal="false">
<span ref="moreTrigger" class="flex shrink-0">
<DropdownMenuTrigger as-child>
<Button variant="ghost" size="icon" class="shortcut-toolbar-button shrink-0" :class="[dropdownOnly ? 'h-8 w-7 rounded-l-none' : 'size-7', { 'bg-accent text-accent-foreground': menuOpen }]" :aria-label="t('pluginPlatform.shortcutsMore', { count: overflowEntries.length })">
<Button
variant="ghost"
size="icon"
class="shortcut-toolbar-button shrink-0"
:class="[dropdownOnly ? 'h-8 w-7 rounded-l-none' : 'size-7', { 'bg-accent text-accent-foreground': menuOpen }]"
:aria-label="overflowEntries.length ? t('pluginPlatform.shortcutsMore', { count: overflowEntries.length }) : t('pluginPlatform.shortcutsSettings')"
>
<ChevronDown class="size-3.5 transition-transform" :class="{ 'rotate-180': menuOpen }" />
</Button>
</DropdownMenuTrigger>
@@ -166,15 +187,28 @@ onScopeDispose(() => {
<span class="min-w-0 flex-1 truncate" :title="entry.label">{{ entry.label }}</span>
<span v-if="isActive(entry)" class="size-1.5 shrink-0 rounded-full bg-green-500" aria-hidden="true" />
</DropdownMenuItem>
<DropdownMenuItem v-if="showSettingsEntry" data-plugin-shortcut-settings :text-value="t('pluginPlatform.shortcutsSettings')" class="relative min-h-8 gap-2 rounded-sm text-xs" @select="activateSettings">
<span v-if="overflowEntries.length" class="pointer-events-none absolute inset-x-2 top-0 h-px bg-border/60" aria-hidden="true" />
<Settings2 class="size-4 shrink-0 text-foreground" />
<span class="min-w-0 flex-1 truncate">{{ t("pluginPlatform.shortcutsSettings") }}</span>
</DropdownMenuItem>
</div>
</DropdownMenuContent>
</DropdownMenu>
<LightTooltip v-if="showSettingsEntry && !hasMenu" :text="t('pluginPlatform.shortcutsSettings')" :disabled="drag.active" side="bottom" content-class="shortcut-toolbar-tooltip">
<Button variant="ghost" size="icon" data-plugin-shortcut-settings class="shortcut-toolbar-button relative size-7 shrink-0" :aria-label="t('pluginPlatform.shortcutsSettings')" @click="activateSettings">
<span v-if="inlineEntries.length" class="pointer-events-none absolute -left-0.5 inset-y-1 w-px bg-border/60" aria-hidden="true" />
<Settings2 class="size-4 text-foreground" />
</Button>
</LightTooltip>
<Teleport to="body">
<div v-if="drag.active" class="fixed inset-0 z-[2147483646] cursor-grabbing touch-none select-none" aria-hidden="true" />
<div
v-if="drag.active && draggedEntry"
class="pointer-events-none fixed z-[2147483647] flex max-w-xs items-center gap-2 rounded-md border border-primary/50 bg-popover px-2 py-1.5 text-xs text-popover-foreground shadow-md"
:style="{ left: `${drag.x + 12}px`, top: `${drag.y + 12}px` }"
ref="preview"
data-shortcut-drag-preview
class="pointer-events-none fixed z-[2147483647] flex w-max max-w-xs overflow-hidden items-center gap-2 rounded-md border border-primary/50 bg-popover px-2 py-1.5 text-xs text-popover-foreground shadow-md"
:style="previewStyle"
aria-hidden="true"
>
<PluginIcon :plugin-id="draggedEntry.pluginId" :icon="draggedEntry.icon" class="size-4 [&_svg]:text-current" />
@@ -1,6 +1,6 @@
// @vitest-environment happy-dom
import { createApp, nextTick, type App, type ComponentPublicInstance } from "vue";
import { createApp, h, ref, nextTick, type App, type ComponentPublicInstance } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { InstalledPlugin, PluginRepositoryCatalogResult } from "@/types/database";
import { formatMarketplaceReleasedDate, type MarketplacePluginListing } from "@/lib/plugins/pluginMarketplace";
@@ -65,6 +65,7 @@ vi.mock("@/components/plugins/PluginShortcutSettings.vue", async () => ({ defaul
import PluginContributionsPanel from "@/components/plugins/PluginContributionsPanel.vue";
type PanelState = {
activeSection: "marketplace" | "installed" | "settings";
batchRunning: boolean;
batchMode: boolean;
marketplaceViewMode: "grid" | "list";
@@ -939,3 +940,49 @@ describe("PluginContributionsPanel single uninstall outcomes", () => {
expect(state.error).toBe('pluginPlatform.batchRefreshFailed:{"error":"refresh offline"}');
});
});
describe("PluginContributionsPanel settings navigation", () => {
it.each(["marketplace", "installed"] as const)("preserves navigation to %s while the initial refresh is pending", async (section) => {
app.unmount();
const pending = deferred<InstalledPlugin[]>();
mocks.listPlugins.mockReturnValue(pending.promise);
app = createApp(PluginContributionsPanel, { focusTarget: { section: "settings" } });
const instance = app.mount(host) as ComponentPublicInstance & { $: { setupState: PanelState } };
const current = instance.$.setupState;
expect(current.activeSection).toBe("settings");
current.activeSection = section;
await nextTick();
pending.resolve([installed("a")]);
await flushUi();
expect(current.activeSection).toBe(section);
});
it.each(["empty", "installed", "load-failure"])("opens and reopens settings without depending on plugin loading (%s)", async (scenario) => {
app.unmount();
host.remove();
host = document.createElement("div");
document.body.append(host);
if (scenario === "load-failure") mocks.listPlugins.mockRejectedValue(new Error("unavailable"));
else mocks.listPlugins.mockResolvedValue(scenario === "empty" ? [] : [installed("a")]);
const focus = ref<{ section: "settings" }>({ section: "settings" });
let panel!: ComponentPublicInstance;
app = createApp({
render: () =>
h(PluginContributionsPanel, {
focusTarget: focus.value,
ref: (value) => {
panel = value as ComponentPublicInstance;
},
}),
});
app.mount(host);
const current = (panel as ComponentPublicInstance & { $: { setupState: PanelState } }).$.setupState;
expect(current.activeSection).toBe("settings");
await flushUi();
expect(current.activeSection).toBe("settings");
current.activeSection = "marketplace";
focus.value = { section: "settings" };
await nextTick();
expect(current.activeSection).toBe("settings");
});
});