feat(plugins): add settings shortcut entry and drag edge avoidance
This commit is contained in:
1 parent
fd6b7bd502
commit
e444c15e0c
32 files changed
+483
-34
No files matched your search
@@ -96,7 +96,7 @@ import { openQueryResultArchiveFile } from "@/lib/query/queryResultArchiveFile";
|
||||
import { activeTabExternalSqlFileTarget, rememberExternalSqlFileTarget, resolveExternalSqlFileTarget, resolveExternalSqlFileTargetForActiveTab, unassociatedExternalSqlFileTarget, type ExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";
|
||||
import { externalSqlFileOpenErrorMessage, externalSqlEditorMaxBytes, isSqlFilePath, readBrowserSqlFile, sqlFileTitleFromPath } from "@/lib/sql/sqlFileOpen";
|
||||
import type { ConnectionConfig, DatabaseType, ObjectBrowserFilter, ObjectSourceKind, QueryTab, TabOutputView, TreeNode } from "@/types/database";
|
||||
import type { PluginCenterFocus } from "@/lib/plugins/pluginCenterNavigation";
|
||||
import { OPEN_PLUGIN_SETTINGS, type PluginCenterFocus } from "@/lib/plugins/pluginCenterNavigation";
|
||||
import { parsePluginInstallDeepLink } from "@/lib/plugins/pluginInstallDeepLink";
|
||||
import { createFrontendPluginRegistry } from "@/lib/plugins/frontendPlugin";
|
||||
import { parseConnectionDeepLink, parseConnectionDeepLinkUpdate, type ConnectionDeepLinkDraft, type ConnectionDeepLinkUpdate } from "@/lib/connection/connectionDeepLink";
|
||||
@@ -1276,6 +1276,8 @@ function openPluginCenterPage(focus?: PluginCenterFocus | null) {
|
||||
activateMainContentSurface("pluginCenter");
|
||||
}
|
||||
|
||||
provide(OPEN_PLUGIN_SETTINGS, () => openPluginCenterPage({ section: "settings" }));
|
||||
|
||||
function closePluginCenterPage() {
|
||||
pluginCenterTabOpen.value = false;
|
||||
pluginCenterFocus.value = null;
|
||||
|
||||
@@ -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" />
|
||||
|
||||
+48
-1
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { createApp, h, nextTick, reactive, ref } from "vue";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { useCursorFloatingPosition } from "../useCursorFloatingPosition";
|
||||
|
||||
let app: ReturnType<typeof createApp>;
|
||||
let host: HTMLDivElement;
|
||||
afterEach(() => {
|
||||
app?.unmount();
|
||||
host?.remove();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("remeasures content and window changes, limits long previews, and cleans up observers", async () => {
|
||||
vi.stubGlobal("innerWidth", 300);
|
||||
vi.stubGlobal("innerHeight", 200);
|
||||
let resized!: () => void;
|
||||
const disconnect = vi.fn();
|
||||
vi.stubGlobal(
|
||||
"ResizeObserver",
|
||||
class {
|
||||
constructor(callback: () => void) {
|
||||
resized = callback;
|
||||
}
|
||||
observe() {}
|
||||
disconnect = disconnect;
|
||||
},
|
||||
);
|
||||
const removeListener = vi.spyOn(window, "removeEventListener");
|
||||
let contentWidth = 180;
|
||||
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
|
||||
const width = Math.min(contentWidth, parseFloat(this.style.maxWidth.split(",")[1]));
|
||||
return { width, height: 32 } as DOMRect;
|
||||
});
|
||||
const cursor = reactive({ x: 290, y: 190 });
|
||||
const visible = ref(true);
|
||||
app = createApp({
|
||||
setup() {
|
||||
const preview = ref<HTMLElement | null>(null);
|
||||
const style = useCursorFloatingPosition(preview, cursor);
|
||||
return () => (visible.value ? h("div", { ref: preview, style: style.value }) : null);
|
||||
},
|
||||
});
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
app.mount(host);
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
const preview = host.firstElementChild as HTMLElement;
|
||||
expect(preview.style.left).toBe("98px");
|
||||
expect(preview.style.top).toBe("146px");
|
||||
contentWidth = 1000;
|
||||
resized();
|
||||
await nextTick();
|
||||
expect(preview.style.left).toBe("8px");
|
||||
expect(preview.style.maxWidth).toBe("min(20rem, 284px)");
|
||||
vi.stubGlobal("innerWidth", 160);
|
||||
window.dispatchEvent(new Event("resize"));
|
||||
await nextTick();
|
||||
expect(preview.style.maxWidth).toBe("min(20rem, 144px)");
|
||||
expect(preview.style.left).toBe("8px");
|
||||
visible.value = false;
|
||||
await nextTick();
|
||||
expect(disconnect).toHaveBeenCalledOnce();
|
||||
expect(removeListener).toHaveBeenCalledWith("resize", expect.any(Function));
|
||||
});
|
||||
@@ -76,6 +76,16 @@ async function setup() {
|
||||
};
|
||||
}
|
||||
describe("shortcut sidebar height", () => {
|
||||
it("reserves the title row as well as 120px for the connection tree", async () => {
|
||||
const { sizing, savedHeight, setTotal } = await setup();
|
||||
const header = document.createElement("div");
|
||||
header.setAttribute("data-shortcut-header", "");
|
||||
Object.defineProperty(header, "offsetHeight", { get: () => 32 });
|
||||
root.querySelector("nav")!.append(header);
|
||||
savedHeight.value = 500;
|
||||
setTotal(300);
|
||||
expect(sizing.height.value).toBe(142);
|
||||
});
|
||||
it("does not attach a resize observer after disposal during a pending measurement", async () => {
|
||||
const observe = vi.fn();
|
||||
vi.stubGlobal(
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { ref, watch, type CSSProperties, type Ref } from "vue";
|
||||
import { floatingCursorPosition } from "@/lib/common/floatingViewportPosition";
|
||||
|
||||
/** Measure after mounting and whenever the preview or viewport changes. Coordinates are CSS pixels. */
|
||||
export function useCursorFloatingPosition(element: Ref<HTMLElement | null>, cursor: { x: number; y: number }, preferredSide: () => "left" | "right" = () => "right") {
|
||||
const style = ref<CSSProperties>({ visibility: "hidden" });
|
||||
function update() {
|
||||
const preview = element.value;
|
||||
if (!preview) return;
|
||||
const width = window.innerWidth;
|
||||
const height = window.innerHeight;
|
||||
// Apply constraints before measuring so truncation and narrow windows use the actual rendered size.
|
||||
preview.style.maxWidth = `min(20rem, ${Math.max(0, width - 16)}px)`;
|
||||
preview.style.maxHeight = `${Math.max(0, height - 16)}px`;
|
||||
const position = floatingCursorPosition(cursor, preview.getBoundingClientRect(), { width, height }, preferredSide());
|
||||
style.value = { left: `${position.x}px`, top: `${position.y}px`, maxWidth: preview.style.maxWidth, maxHeight: preview.style.maxHeight };
|
||||
}
|
||||
watch([element, () => cursor.x, () => cursor.y, preferredSide], update, { flush: "post" });
|
||||
watch(
|
||||
element,
|
||||
(preview, _, onCleanup) => {
|
||||
if (!preview) {
|
||||
style.value = { visibility: "hidden" };
|
||||
return;
|
||||
}
|
||||
const observer = new ResizeObserver(update);
|
||||
observer.observe(preview);
|
||||
window.addEventListener("resize", update);
|
||||
onCleanup(() => {
|
||||
observer.disconnect();
|
||||
window.removeEventListener("resize", update);
|
||||
});
|
||||
},
|
||||
{ flush: "post" },
|
||||
);
|
||||
return style;
|
||||
}
|
||||
@@ -24,8 +24,9 @@ export function usePluginShortcutHeight(options: { section: Ref<HTMLElement | nu
|
||||
if (!section || !scroll || !options.sidebarList.value) return;
|
||||
const tree = section.previousElementSibling as HTMLElement | null;
|
||||
const divider = section.querySelector<HTMLElement>("[data-shortcut-resize]");
|
||||
available.value = (tree?.offsetHeight ?? 0) + section.offsetHeight - (divider?.offsetHeight ?? 0);
|
||||
const item = scroll.querySelector<HTMLElement>("[data-shortcut-id]");
|
||||
const header = section.querySelector<HTMLElement>("[data-shortcut-header]");
|
||||
available.value = (tree?.offsetHeight ?? 0) + section.offsetHeight - (divider?.offsetHeight ?? 0) - (header?.offsetHeight ?? 0);
|
||||
const item = scroll.querySelector<HTMLElement>("[data-shortcut-id], [data-plugin-shortcut-settings]");
|
||||
const grid = scroll.firstElementChild;
|
||||
itemSize.value = item?.offsetHeight || 28;
|
||||
gap.value = grid ? parseFloat(getComputedStyle(grid).gap) || 0 : 0;
|
||||
|
||||
@@ -105,6 +105,9 @@ export default withEnglishFallback({
|
||||
missingConnection: "Silinmiş bağlantı ({id})",
|
||||
revokeFailed: "Giriş ləğv edilmədi: {message}",
|
||||
},
|
||||
shortcutsHeading: "Plaginlər",
|
||||
shortcutsSettings: "Plagin parametrləri",
|
||||
shortcutsShowSettings: "Plagin parametrləri qısayolunu göstər",
|
||||
shortcutsPluginCenter: "Plagin mərkəzinin yanında (açılan menyu)",
|
||||
shortcutsToolbar: "Yeniləmə düyməsinin solunda (üzən)",
|
||||
shortcutsToolbarCount: "Görünən nişanların sayı",
|
||||
|
||||
@@ -205,6 +205,9 @@ export default {
|
||||
globalSettingsTitle: "Global settings",
|
||||
shortcutsTitle: "Plugin shortcuts",
|
||||
shortcutsDescription: "Choose where plugin shortcuts appear. Drag icons to reorder them.",
|
||||
shortcutsHeading: "Plugins",
|
||||
shortcutsSettings: "Plugin settings",
|
||||
shortcutsShowSettings: "Show plugin settings shortcut",
|
||||
shortcutsEnabled: "Show plugin shortcuts",
|
||||
shortcutsPosition: "Position",
|
||||
shortcutsBottom: "Connection tree bottom",
|
||||
|
||||
@@ -208,6 +208,9 @@ export default withEnglishFallback({
|
||||
globalSettingsTitle: "Configuración global",
|
||||
shortcutsTitle: "Accesos a complementos",
|
||||
shortcutsDescription: "Elige la ubicación de los accesos. Arrastra los iconos para reordenarlos.",
|
||||
shortcutsHeading: "Plugins",
|
||||
shortcutsSettings: "Ajustes de plugins",
|
||||
shortcutsShowSettings: "Mostrar acceso a ajustes de plugins",
|
||||
shortcutsEnabled: "Mostrar accesos a complementos",
|
||||
shortcutsPosition: "Ubicación",
|
||||
shortcutsBottom: "Debajo del árbol de conexiones",
|
||||
|
||||
@@ -208,6 +208,9 @@ export default withEnglishFallback({
|
||||
globalSettingsTitle: "Impostazioni globali",
|
||||
shortcutsTitle: "Scorciatoie dei plugin",
|
||||
shortcutsDescription: "Scegli la posizione delle scorciatoie. Trascina le icone per riordinarle.",
|
||||
shortcutsHeading: "Plugin",
|
||||
shortcutsSettings: "Impostazioni plugin",
|
||||
shortcutsShowSettings: "Mostra collegamento alle impostazioni plugin",
|
||||
shortcutsEnabled: "Mostra scorciatoie dei plugin",
|
||||
shortcutsPosition: "Posizione",
|
||||
shortcutsBottom: "Sotto l’albero delle connessioni",
|
||||
|
||||
@@ -208,6 +208,9 @@ export default withEnglishFallback({
|
||||
globalSettingsTitle: "グローバル設定",
|
||||
shortcutsTitle: "プラグインショートカット",
|
||||
shortcutsDescription: "表示位置を選択します。アイコンをドラッグして並べ替えできます。",
|
||||
shortcutsHeading: "プラグイン",
|
||||
shortcutsSettings: "プラグイン設定",
|
||||
shortcutsShowSettings: "プラグイン設定のショートカットを表示",
|
||||
shortcutsEnabled: "プラグインショートカットを表示",
|
||||
shortcutsPosition: "表示位置",
|
||||
shortcutsBottom: "接続ツリーの下部",
|
||||
|
||||
@@ -207,6 +207,9 @@ export default withEnglishFallback({
|
||||
globalSettingsTitle: "전역 설정",
|
||||
shortcutsTitle: "플러그인 바로가기",
|
||||
shortcutsDescription: "표시 위치를 선택하세요. 아이콘을 드래그하여 순서를 변경할 수 있습니다.",
|
||||
shortcutsHeading: "플러그인",
|
||||
shortcutsSettings: "플러그인 설정",
|
||||
shortcutsShowSettings: "플러그인 설정 바로가기 표시",
|
||||
shortcutsEnabled: "플러그인 바로가기 표시",
|
||||
shortcutsPosition: "표시 위치",
|
||||
shortcutsBottom: "연결 트리 하단",
|
||||
|
||||
@@ -208,6 +208,9 @@ export default withEnglishFallback({
|
||||
globalSettingsTitle: "Configurações globais",
|
||||
shortcutsTitle: "Atalhos de plugins",
|
||||
shortcutsDescription: "Escolha a posição dos atalhos. Arraste os ícones para reordená-los.",
|
||||
shortcutsHeading: "Plugins",
|
||||
shortcutsSettings: "Configurações de plugins",
|
||||
shortcutsShowSettings: "Mostrar atalho das configurações de plugins",
|
||||
shortcutsEnabled: "Mostrar atalhos de plugins",
|
||||
shortcutsPosition: "Posição",
|
||||
shortcutsBottom: "Abaixo da árvore de conexões",
|
||||
|
||||
@@ -155,6 +155,9 @@ export default withEnglishFallback({
|
||||
globalSettingsTitle: "Общие настройки",
|
||||
shortcutsTitle: "Быстрый доступ к плагинам",
|
||||
shortcutsDescription: "Выберите расположение панели. Перетаскивайте значки, чтобы изменить их порядок.",
|
||||
shortcutsHeading: "Плагины",
|
||||
shortcutsSettings: "Настройки плагинов",
|
||||
shortcutsShowSettings: "Показывать ярлык настроек плагинов",
|
||||
shortcutsEnabled: "Показывать быстрый доступ к плагинам",
|
||||
shortcutsPosition: "Расположение",
|
||||
shortcutsBottom: "Под деревом подключений",
|
||||
|
||||
@@ -107,6 +107,9 @@ export default withEnglishFallback({
|
||||
missingConnection: "Silinmiş bağlantı ({id})",
|
||||
revokeFailed: "Erişim iptal edilemedi: {message}",
|
||||
},
|
||||
shortcutsHeading: "Eklentiler",
|
||||
shortcutsSettings: "Eklenti ayarları",
|
||||
shortcutsShowSettings: "Eklenti ayarları kısayolunu göster",
|
||||
shortcutsPluginCenter: "Eklenti merkezinin yanında (açılır menü)",
|
||||
shortcutsToolbar: "Güncelle düğmesinin solunda (kayan)",
|
||||
shortcutsToolbarCount: "Görünür simge sayısı",
|
||||
|
||||
@@ -130,6 +130,9 @@ export default withEnglishFallback({
|
||||
globalSettingsTitle: "全局配置",
|
||||
shortcutsTitle: "插件快捷入口",
|
||||
shortcutsDescription: "选择插件快捷入口的显示位置,拖动图标可调整顺序。",
|
||||
shortcutsHeading: "插件",
|
||||
shortcutsSettings: "插件设置",
|
||||
shortcutsShowSettings: "显示“插件设置”快捷入口",
|
||||
shortcutsEnabled: "显示插件快捷入口",
|
||||
shortcutsPosition: "显示位置",
|
||||
shortcutsBottom: "连接树底部",
|
||||
|
||||
@@ -208,6 +208,9 @@ export default withEnglishFallback({
|
||||
globalSettingsTitle: "全域設定",
|
||||
shortcutsTitle: "外掛程式快捷入口",
|
||||
shortcutsDescription: "選擇外掛程式快捷入口的顯示位置,拖曳圖示可調整順序。",
|
||||
shortcutsHeading: "外掛",
|
||||
shortcutsSettings: "外掛設定",
|
||||
shortcutsShowSettings: "顯示「外掛設定」快捷入口",
|
||||
shortcutsEnabled: "顯示外掛程式快捷入口",
|
||||
shortcutsPosition: "顯示位置",
|
||||
shortcutsBottom: "連線樹底部",
|
||||
|
||||
@@ -1,7 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { floatingArrowOffset, floatingViewportShift } from "@/lib/common/floatingViewportPosition";
|
||||
import { floatingArrowOffset, floatingCursorPosition, floatingViewportShift } from "@/lib/common/floatingViewportPosition";
|
||||
|
||||
describe("floating viewport position", () => {
|
||||
it.each([
|
||||
{ cursor: { x: 400, y: 300 }, side: "right", expected: { x: 412, y: 312 } },
|
||||
{ cursor: { x: 400, y: 300 }, side: "left", expected: { x: 188, y: 312 } },
|
||||
{ cursor: { x: 790, y: 590 }, side: "right", expected: { x: 578, y: 538 } },
|
||||
{ cursor: { x: 2, y: 2 }, side: "left", expected: { x: 14, y: 14 } },
|
||||
{ cursor: { x: -30, y: -30 }, side: "left", expected: { x: 8, y: 8 } },
|
||||
{ cursor: { x: 900, y: 700 }, side: "right", expected: { x: 592, y: 552 } },
|
||||
] as const)("follows and flips around $cursor with $side preference", ({ cursor, side, expected }) => {
|
||||
expect(floatingCursorPosition(cursor, { width: 200, height: 40 }, { width: 800, height: 600 }, side)).toEqual(expected);
|
||||
});
|
||||
|
||||
it("clamps when neither side has enough room, including oversized surfaces", () => {
|
||||
expect(floatingCursorPosition({ x: 150, y: 40 }, { width: 284, height: 64 }, { width: 300, height: 80 })).toEqual({ x: 8, y: 8 });
|
||||
expect(floatingCursorPosition({ x: 1, y: 1 }, { width: 200, height: 40 }, { width: 4, height: 4 })).toEqual({ x: 2, y: 2 });
|
||||
});
|
||||
|
||||
it("moves a floating element inside each viewport edge", () => {
|
||||
expect(floatingViewportShift({ left: -24, right: 296, top: 40, bottom: 80 }, { width: 800, height: 600 })).toEqual({ x: 32, y: 0 });
|
||||
expect(floatingViewportShift({ left: 600, right: 840, top: 40, bottom: 80 }, { width: 800, height: 600 })).toEqual({ x: -48, y: 0 });
|
||||
|
||||
@@ -10,6 +10,23 @@ export interface FloatingViewport {
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** Place a cursor-following surface, flipping each axis before clamping to the viewport. */
|
||||
export function floatingCursorPosition(cursor: { x: number; y: number }, size: { width: number; height: number }, viewport: FloatingViewport, preferredSide: "left" | "right" = "right", gap = 12, margin = 8): { x: number; y: number } {
|
||||
function axis(pointer: number, length: number, extent: number, before: boolean) {
|
||||
const inset = Math.min(margin, Math.max(0, extent / 2));
|
||||
const maximum = Math.max(inset, extent - inset - length);
|
||||
const preferred = before ? pointer - gap - length : pointer + gap;
|
||||
const alternative = before ? pointer + gap : pointer - gap - length;
|
||||
const fits = (value: number) => value >= inset && value + length <= extent - inset;
|
||||
const position = fits(preferred) ? preferred : fits(alternative) ? alternative : preferred;
|
||||
return Math.min(maximum, Math.max(inset, position));
|
||||
}
|
||||
return {
|
||||
x: axis(cursor.x, size.width, viewport.width, preferredSide === "left"),
|
||||
y: axis(cursor.y, size.height, viewport.height, false),
|
||||
};
|
||||
}
|
||||
|
||||
export function floatingViewportShift(rect: FloatingRect, viewport: FloatingViewport, margin = 8): { x: number; y: number } {
|
||||
let x = 0;
|
||||
let y = 0;
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import type { InjectionKey } from "vue";
|
||||
|
||||
export const OPEN_PLUGIN_SETTINGS: InjectionKey<() => void> = Symbol("open-plugin-settings");
|
||||
|
||||
export interface PluginCenterFocus {
|
||||
section?: "settings";
|
||||
pluginId?: string;
|
||||
providerId?: string;
|
||||
}
|
||||
+4
-2
@@ -45,8 +45,10 @@ describe("plugin shortcuts", () => {
|
||||
expect(clampPluginShortcutHeight(40, 130)).toBe(10);
|
||||
});
|
||||
it("normalizes old and malformed preferences with independent default arrays", () => {
|
||||
expect(normalizePluginShortcutSettings(null)).toEqual({ enabled: true, position: "right-top", order: [], hiddenPluginIds: [], sidebarHeight: null, toolbarCount: 3 });
|
||||
expect(normalizePluginShortcutSettings({ enabled: "false", position: "top", order: [null, "a", "", "a", "b"] })).toEqual({ enabled: true, position: "right-top", order: ["a", "b"], hiddenPluginIds: [], sidebarHeight: null, toolbarCount: 3 });
|
||||
expect(normalizePluginShortcutSettings({ showSettingsEntry: "false" }).showSettingsEntry).toBe(true);
|
||||
expect(normalizePluginShortcutSettings({ showSettingsEntry: false }).showSettingsEntry).toBe(false);
|
||||
expect(normalizePluginShortcutSettings(null)).toEqual({ enabled: true, position: "right-top", order: [], hiddenPluginIds: [], sidebarHeight: null, toolbarCount: 3, showSettingsEntry: true });
|
||||
expect(normalizePluginShortcutSettings({ enabled: "false", position: "top", order: [null, "a", "", "a", "b"] })).toEqual({ enabled: true, position: "right-top", order: ["a", "b"], hiddenPluginIds: [], sidebarHeight: null, toolbarCount: 3, showSettingsEntry: true });
|
||||
expect(normalizePluginShortcutSettings({ enabled: false, position: "sidebar-bottom" }).enabled).toBe(false);
|
||||
});
|
||||
it("includes legacy standalone workbenches and filesystems but not connection-bound surfaces", () => {
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { PluginCommandContribution } from "@/types/database";
|
||||
export type PluginShortcutPosition = "left-top" | "left-bottom" | "right-top" | "right-bottom" | "sidebar-bottom" | "toolbar" | "plugin-center";
|
||||
export interface PluginShortcutSettings {
|
||||
enabled: boolean;
|
||||
showSettingsEntry: boolean;
|
||||
position: PluginShortcutPosition;
|
||||
order: string[];
|
||||
hiddenPluginIds: string[];
|
||||
@@ -17,6 +18,7 @@ export function normalizePluginShortcutSettings(value: unknown): PluginShortcutS
|
||||
const strings = (values: unknown): string[] => (Array.isArray(values) ? [...new Set(values.filter((id): id is string => typeof id === "string" && id.length > 0))] : []);
|
||||
return {
|
||||
enabled: typeof input.enabled === "boolean" ? input.enabled : true,
|
||||
showSettingsEntry: typeof input.showSettingsEntry === "boolean" ? input.showSettingsEntry : true,
|
||||
position: position === "left" ? "left-top" : position === "left-top" || position === "left-bottom" || position === "right-bottom" || position === "sidebar-bottom" || position === "toolbar" || position === "plugin-center" ? position : "right-top",
|
||||
order: strings(input.order),
|
||||
hiddenPluginIds: strings(input.hiddenPluginIds),
|
||||
|
||||
@@ -18,7 +18,7 @@ describe("plugin shortcut persistence", () => {
|
||||
});
|
||||
const first = useSettingsStore();
|
||||
await first.initEditorSettings();
|
||||
const pluginShortcuts = { enabled: false, position, order: ["b", "missing", "a"], hiddenPluginIds: ["hidden"], sidebarHeight: 132, toolbarCount: 6 };
|
||||
const pluginShortcuts = { enabled: false, position, order: ["b", "missing", "a"], hiddenPluginIds: ["hidden"], sidebarHeight: 132, toolbarCount: 6, showSettingsEntry: false };
|
||||
await first.updateEditorSettingsAndPersist({ pluginShortcuts });
|
||||
setActivePinia(createPinia());
|
||||
const second = useSettingsStore();
|
||||
|
||||
Reference in new issue
Block a user