fix(ai): compact composer controls based on overflow

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-09-26 06:51:19 +08:00
1 parent fe8737550c
commit 2ad6f4c98e
2 files changed
+224 -39

No files matched your search

@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed, defineAsyncComponent, h, nextTick, onMounted, onUnmounted, reactive, ref, toRaw, watch, type Component } from "vue";
import { uuid } from "@/lib/common/utils";
import { deferUntilPanelResizeEnd } from "@/lib/app/panelResizeState";
import { useI18n } from "vue-i18n";
import { translateBackendError } from "@/i18n/backend-errors";
import {
@@ -1200,10 +1201,15 @@ const AI_TEXTAREA_HEIGHT_STORAGE_KEY = "dbx-ai-textarea-height";
const textareaHeight = ref<number>(AI_TEXTAREA_MIN_HEIGHT_PX);
const assistantRootRef = ref<HTMLElement | null>(null);
const promptPanelRef = ref<HTMLElement | null>(null);
const compactContextControls = ref(false);
const compactActionControls = ref(false);
const isResizing = ref<boolean>(false);
let resizeStartY = 0;
let resizeStartHeight = 0;
let promptPanelResizeObserver: ResizeObserver | undefined;
let responsiveControlMeasureFrame: number | null = null;
let responsiveControlMeasureForce = false;
let lastResponsiveControlWidth: number | null = null;
interface AiTableMentionCandidate {
kind: "table";
@@ -5037,7 +5043,9 @@ onMounted(async () => {
if (typeof ResizeObserver !== "undefined" && assistantRootRef.value) {
promptPanelResizeObserver = new ResizeObserver(handlePanelResize);
promptPanelResizeObserver.observe(assistantRootRef.value);
if (promptPanelRef.value) promptPanelResizeObserver.observe(promptPanelRef.value);
}
scheduleResponsiveControlMeasurement(true);
});
function maxTextareaHeight() {
@@ -5054,8 +5062,91 @@ function clampTextareaHeight(height: number) {
function handlePanelResize() {
textareaHeight.value = clampTextareaHeight(textareaHeight.value);
scheduleResponsiveControlMeasurement();
}
function hasHorizontalOverflow(element: HTMLElement | null): boolean {
return !!element && element.scrollWidth > element.clientWidth + 1;
}
function hasOverflowingLabel(element: HTMLElement | null, selector: string): boolean {
if (!element) return false;
return Array.from(element.querySelectorAll<HTMLElement>(selector)).some((label) => label.scrollWidth > label.clientWidth + 1);
}
async function measureResponsiveControls(force = false) {
const panel = promptPanelRef.value;
if (!panel) return;
// Reading clientWidth/scrollWidth here forces a document-wide synchronous
// relayout, and the AI panel divider drag fires resize events every frame.
// Skip measurements while the drag is in flight and re-measure once at the end.
if (
deferUntilPanelResizeEnd(() => {
void measureResponsiveControls(force);
})
)
return;
const panelWidth = panel.clientWidth;
if (!force && lastResponsiveControlWidth === panelWidth) return;
// Measure the full labels before deciding to compact. This lets a wide
// composer recover from icon mode after it grows, while the actual
// overflow checks decide independently for the context and action rows.
if (compactContextControls.value || compactActionControls.value) {
compactContextControls.value = false;
compactActionControls.value = false;
await nextTick();
}
const contextRow = panel.querySelector<HTMLElement>("[data-ai-composer-context-row]");
const actionRow = panel.querySelector<HTMLElement>("[data-ai-composer-actions]");
const contextOverflow = hasHorizontalOverflow(contextRow) || hasOverflowingLabel(contextRow, ".ai-template-selector-label, .ai-skills-selector-label");
const actionOverflow = hasHorizontalOverflow(actionRow) || hasOverflowingLabel(actionRow, ".ai-mode-action-label, .ai-model-selector-label, .ai-prompt-queue-label");
compactContextControls.value = contextOverflow;
compactActionControls.value = actionOverflow;
lastResponsiveControlWidth = panelWidth;
}
function scheduleResponsiveControlMeasurement(force = false) {
responsiveControlMeasureForce ||= force;
if (responsiveControlMeasureFrame !== null) return;
const measure = () => {
responsiveControlMeasureFrame = null;
const forceMeasure = responsiveControlMeasureForce;
responsiveControlMeasureForce = false;
void measureResponsiveControls(forceMeasure);
};
if (typeof window !== "undefined" && typeof window.requestAnimationFrame === "function") {
responsiveControlMeasureFrame = window.requestAnimationFrame(measure);
} else {
void nextTick(measure);
}
}
watch(
() => [
templateSelectorTriggerLabel.value,
selectedSkillIds.value.join(","),
modeActionTriggerLabel.value,
activeFullConfig.value?.model,
boundConnectionId.value,
selectedDatabaseLabel.value,
boundSchema.value,
connectionStore.connections.length,
showAiDatabaseSelector.value,
showAiSchemaSelector.value,
settings.aiConfigs.length,
hasActiveRunForCurrentConversation.value,
isGenerating.value,
pluginContext.value?.pluginName,
pluginContext.value?.title,
currentQueuedInput.value?.text,
],
() => scheduleResponsiveControlMeasurement(true),
{ flush: "post" },
);
function startResize(event: MouseEvent) {
event.preventDefault();
isResizing.value = true;
@@ -5116,6 +5207,11 @@ onUnmounted(() => {
document.removeEventListener("dbx:tauri-file-drop", onTauriFileDrop as EventListener);
window.removeEventListener(DBX_TABLE_REFERENCE_DROP_EVENT, onTableReferenceDropEvent);
promptPanelResizeObserver?.disconnect();
if (responsiveControlMeasureFrame !== null && typeof window !== "undefined" && typeof window.cancelAnimationFrame === "function") {
window.cancelAnimationFrame(responsiveControlMeasureFrame);
responsiveControlMeasureFrame = null;
}
responsiveControlMeasureForce = false;
});
function triggerAction(action: AiAction, instruction?: string) {
@@ -5760,7 +5856,7 @@ async function openExternalUrl(url: string) {
</div>
<div class="resize-handle" @mousedown="startResize"></div>
<div class="px-2 pb-2 pt-1">
<div data-ai-composer-context-row :class="['ai-prompt-context-row mb-1 flex items-center gap-x-1 text-xs text-foreground/80', showAiSchemaSelector && 'ai-prompt-context-row--schema']">
<div data-ai-composer-context-row :class="['ai-prompt-context-row mb-1 flex min-w-0 items-center gap-x-1 text-xs text-foreground/80', showAiSchemaSelector && 'ai-prompt-context-row--schema', compactContextControls && 'ai-prompt-context-row--compact']">
<details v-if="pluginContext" class="min-w-0 flex-1" data-ai-plugin-context>
<summary class="cursor-pointer truncate">{{ pluginContext.pluginName }} · {{ pluginContext.title }}</summary>
<pre class="max-h-56 overflow-auto whitespace-pre-wrap break-all p-2 text-[11px]">{{ pluginContextText(pluginContext) }}</pre>
@@ -5775,7 +5871,7 @@ async function openExternalUrl(url: string) {
:placeholder="t('editor.selectConnection')"
:search-placeholder="t('editor.searchConnection')"
:empty-text="t('grid.noSearchResults')"
:trigger-class="['h-5 px-1 text-foreground/80', showAiSchemaSelector && 'min-w-0 max-w-56 flex-1']"
:trigger-class="['h-5 min-w-0 max-w-full px-1 text-foreground/80', showAiSchemaSelector && 'max-w-56 flex-1']"
trigger-icon-class="h-3 w-3"
list-class="w-72 max-w-[calc(100vw-2rem)]"
@update:model-value="(v) => changeConnection(v)"
@@ -5790,7 +5886,7 @@ async function openExternalUrl(url: string) {
"
>
<PopoverTrigger as-child>
<Button variant="ghost" :title="selectedDatabaseLabel" :class="['h-5 max-w-64 justify-start border-0 p-0 px-1 text-xs font-normal text-foreground/80 shadow-none', showAiSchemaSelector && 'min-w-0 flex-1']">
<Button variant="ghost" :title="selectedDatabaseLabel" :class="['h-5 min-w-0 max-w-64 justify-start border-0 p-0 px-1 text-xs font-normal text-foreground/80 shadow-none', showAiSchemaSelector && 'flex-1']">
<span class="truncate">{{ selectedDatabaseLabel }}</span>
</Button>
</PopoverTrigger>
@@ -5883,10 +5979,10 @@ async function openExternalUrl(url: string) {
<!-- Skill selector (read-only user SKILL.md library) -->
<Popover v-model:open="showSkillSelector">
<PopoverTrigger as-child>
<button type="button" class="flex min-w-0 items-center gap-1 rounded-[6px] border px-2 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground" :aria-label="t('ai.skillsEntry')" :title="t('ai.skillsEntry')">
<button type="button" class="ai-skills-selector-trigger flex min-w-0 items-center gap-1 rounded-[6px] border px-2 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground" :aria-label="t('ai.skillsEntry')" :title="t('ai.skillsEntry')">
<Layers class="h-3 w-3" />
<span class="truncate">{{ t("ai.skillsEntry") }}</span>
<span v-if="selectedSkillIds.length" class="rounded-sm bg-primary px-1 text-[10px] font-medium text-primary-foreground">{{ selectedSkillIds.length }}</span>
<span class="ai-skills-selector-label truncate">{{ t("ai.skillsEntry") }}</span>
<span v-if="selectedSkillIds.length" class="ai-skills-selector-count rounded-sm bg-primary px-1 text-[10px] font-medium text-primary-foreground">{{ selectedSkillIds.length }}</span>
</button>
</PopoverTrigger>
<PopoverContent align="end" class="w-72 gap-0 p-1.5">
@@ -6113,7 +6209,7 @@ async function openExternalUrl(url: string) {
<Clock class="h-3.5 w-3.5 shrink-0" />
<span>{{ t("ai.status.longRunningHint") }}</span>
</div>
<div class="flex min-w-0 flex-nowrap items-center gap-1.5 overflow-hidden">
<div data-ai-composer-actions :class="['ai-prompt-action-row flex min-w-0 flex-nowrap items-center gap-1.5 overflow-hidden', compactActionControls && 'ai-prompt-action-row--compact']">
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon" class="h-7 w-7 shrink-0" :disabled="isGenerating" @click="selectCsvFile">
@@ -6127,13 +6223,17 @@ async function openExternalUrl(url: string) {
</TooltipContent>
</Tooltip>
<!-- Combined mode + action selector -->
<span v-if="pluginContext" class="shrink-0 text-xs text-muted-foreground">{{ t("ai.modes.ask") }}</span>
<span v-if="pluginContext" class="ai-mode-static-trigger flex shrink-0 items-center gap-1 text-xs text-muted-foreground" :title="t('ai.modes.ask')">
<MessageSquarePlus class="h-3 w-3" aria-hidden="true" />
<span class="ai-mode-action-label" aria-hidden="true">{{ t("ai.modes.ask") }}</span>
<span class="sr-only">{{ t("ai.modes.ask") }}</span>
</span>
<Popover v-else v-model:open="modeActionOpen">
<PopoverTrigger as-child>
<button type="button" class="flex shrink-0 items-center gap-1 whitespace-nowrap rounded-[6px] border px-2 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground" :aria-label="modeActionTriggerLabel">
<button type="button" class="ai-mode-action-trigger flex shrink-0 items-center gap-1 whitespace-nowrap rounded-[6px] border px-2 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground" :aria-label="modeActionTriggerLabel" :title="modeActionTriggerLabel">
<component :is="modeIcon" class="h-3 w-3" />
<span>{{ modeActionTriggerLabel }}</span>
<svg class="h-3 w-3 shrink-0 opacity-60" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m6 9 6 6 6-6" /></svg>
<span class="ai-mode-action-label">{{ modeActionTriggerLabel }}</span>
<svg class="ai-mode-action-chevron h-3 w-3 shrink-0 opacity-60" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m6 9 6 6 6-6" /></svg>
</button>
</PopoverTrigger>
<PopoverContent align="start" class="w-56 gap-0 p-1.5" @click.stop>
@@ -6171,12 +6271,17 @@ async function openExternalUrl(url: string) {
</template>
</PopoverContent>
</Popover>
<span class="min-w-0 flex-1" />
<span class="ai-prompt-action-spacer min-w-0 flex-1" />
<template v-if="settings.aiConfigs.length > 0">
<!-- Combined provider + model selector -->
<Popover v-model:open="providerSelectorOpen">
<PopoverTrigger as-child>
<button type="button" class="min-w-0 flex shrink items-center gap-1.5 max-w-[220px] rounded-[6px] border px-2 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground">
<button
type="button"
class="ai-model-selector-trigger min-w-0 flex shrink items-center gap-1.5 max-w-[220px] rounded-[6px] border px-2 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground"
:aria-label="activeFullConfig?.model || t('ai.selectModel')"
:title="activeFullConfig?.model || t('ai.selectModel')"
>
<AiProviderLogo
:provider="activeFullConfig?.provider ?? 'claude'"
:label="aiConfigProviderLabel(activeFullConfig)"
@@ -6184,8 +6289,8 @@ async function openExternalUrl(url: string) {
:icon-path="activeFullConfig ? getAiProviderPreset(activeFullConfig.provider, activeFullConfig.endpoint).iconPath : undefined"
class="h-3 w-3 shrink-0"
/>
<span class="min-w-0 truncate">{{ activeFullConfig?.model || t("ai.selectModel") }}</span>
<svg class="h-3 w-3 shrink-0 opacity-60" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m6 9 6 6 6-6" /></svg>
<span class="ai-model-selector-label min-w-0 truncate">{{ activeFullConfig?.model || t("ai.selectModel") }}</span>
<svg class="ai-model-selector-chevron h-3 w-3 shrink-0 opacity-60" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m6 9 6 6 6-6" /></svg>
</button>
</PopoverTrigger>
<PopoverContent align="end" class="max-h-(--reka-popover-content-available-height) w-80 gap-0 overflow-y-auto p-1.5" @open-auto-focus.prevent>
@@ -6373,14 +6478,21 @@ async function openExternalUrl(url: string) {
</PopoverContent>
</Popover>
</template>
<button v-if="isGenerating" class="h-7 w-7 shrink-0 rounded-full bg-destructive text-destructive-foreground flex items-center justify-center" :title="t('ai.stopGenerating')" @click="cancelStream">
<button v-if="isGenerating" class="ai-prompt-send-control h-7 w-7 shrink-0 rounded-full bg-destructive text-destructive-foreground flex items-center justify-center" :title="t('ai.stopGenerating')" @click="cancelStream">
<Square class="h-3.5 w-3.5" />
</button>
<button v-else-if="hasActiveRunForCurrentConversation" class="h-7 shrink-0 items-center gap-1 rounded-full bg-foreground px-2.5 text-[11px] font-medium text-background-solid disabled:opacity-30 flex" :disabled="!canSubmitPrompt" :title="t('ai.queueSendHint')" @click="onSendClick">
<button
v-else-if="hasActiveRunForCurrentConversation"
class="ai-prompt-send-control ai-prompt-queue-control h-7 shrink-0 items-center gap-1 rounded-full bg-foreground px-2.5 text-[11px] font-medium text-background-solid disabled:opacity-30 flex"
:disabled="!canSubmitPrompt"
:aria-label="t('ai.queueSend')"
:title="t('ai.queueSendHint')"
@click="onSendClick"
>
<Hourglass class="h-3.5 w-3.5" />
<span>{{ t("ai.queueSend") }}</span>
<span class="ai-prompt-queue-label">{{ t("ai.queueSend") }}</span>
</button>
<button v-else class="h-7 w-7 shrink-0 rounded-full bg-foreground text-background-solid flex items-center justify-center disabled:opacity-30" :disabled="!canSubmitPrompt" @click="send">
<button v-else class="ai-prompt-send-control h-7 w-7 shrink-0 rounded-full bg-foreground text-background-solid flex items-center justify-center disabled:opacity-30" :disabled="!canSubmitPrompt" @click="send">
<ArrowUp class="h-4 w-4" />
</button>
</div>
@@ -6430,28 +6542,66 @@ async function openExternalUrl(url: string) {
</template>
<style scoped>
.ai-prompt-context-container {
container-type: inline-size;
.ai-prompt-context-row--compact .ai-prompt-context-spacer {
flex: 0 0 0;
}
@container (max-width: 28rem) {
.ai-prompt-context-row--schema .ai-prompt-context-spacer {
flex: 0 0 0;
}
.ai-prompt-context-row--compact .ai-template-selector-trigger,
.ai-prompt-context-row--compact .ai-skills-selector-trigger {
flex: 0 0 1.5rem;
width: 1.5rem;
max-width: 1.5rem;
height: 1.5rem;
justify-content: center;
padding: 0;
}
.ai-prompt-context-row--schema .ai-template-selector-trigger {
flex: 0 0 1.5rem;
width: 1.5rem;
max-width: 1.5rem;
height: 1.5rem;
justify-content: center;
padding: 0;
}
.ai-prompt-context-row--compact .ai-template-selector-label,
.ai-prompt-context-row--compact .ai-template-selector-chevron,
.ai-prompt-context-row--compact .ai-skills-selector-label,
.ai-prompt-context-row--compact .ai-skills-selector-count {
display: none;
}
.ai-prompt-context-row--schema .ai-template-selector-label,
.ai-prompt-context-row--schema .ai-template-selector-chevron {
display: none;
}
.ai-prompt-action-row--compact {
gap: 0.25rem;
}
.ai-prompt-action-row--compact .ai-mode-action-trigger,
.ai-prompt-action-row--compact .ai-mode-static-trigger,
.ai-prompt-action-row--compact .ai-model-selector-trigger {
flex: 0 0 1.75rem;
width: 1.75rem;
max-width: 1.75rem;
height: 1.75rem;
justify-content: center;
padding: 0;
}
.ai-prompt-action-row--compact .ai-mode-action-label,
.ai-prompt-action-row--compact .ai-mode-action-chevron,
.ai-prompt-action-row--compact .ai-model-selector-label,
.ai-prompt-action-row--compact .ai-model-selector-chevron {
display: none;
}
.ai-prompt-action-row--compact .ai-model-selector-trigger {
min-width: 1.75rem;
}
.ai-prompt-action-row--compact .ai-prompt-send-control {
flex: 0 0 auto;
}
.ai-prompt-action-row--compact .ai-prompt-queue-control {
width: 1.75rem;
height: 1.75rem;
justify-content: center;
padding: 0;
}
.ai-prompt-action-row--compact .ai-prompt-queue-label {
display: none;
}
.ai-markdown :deep(h1) {
@@ -38,7 +38,7 @@ afterEach(() => {
while (cleanups.length) cleanups.pop()?.();
});
async function mountPanel(aiConfigLoaded: boolean, connection?: ConnectionConfig) {
async function mountPanel(aiConfigLoaded: boolean, connection?: ConnectionConfig, configureSettings?: (settings: ReturnType<typeof useSettingsStore>) => void) {
const pinia = createPinia();
const errors: unknown[] = [];
const app = createApp({ render: () => h(TooltipProvider, () => h(AiAssistant, { connection })) });
@@ -46,7 +46,9 @@ async function mountPanel(aiConfigLoaded: boolean, connection?: ConnectionConfig
app.use(i18n);
app.config.errorHandler = (error) => errors.push(error);
app.config.warnHandler = () => {};
useSettingsStore(pinia).isAiConfigLoaded = aiConfigLoaded;
const settings = useSettingsStore(pinia);
settings.isAiConfigLoaded = aiConfigLoaded;
configureSettings?.(settings);
if (connection) useConnectionStore(pinia).connections = [connection];
const container = document.createElement("div");
document.body.append(container);
@@ -69,6 +71,39 @@ describe("AiAssistant mount", () => {
expect((await mountPanel(false)).errors.map(String)).toEqual([]);
});
it("renders compactable composer controls with accessible labels", async () => {
const { errors, container } = await mountPanel(true, undefined, (settings) => {
settings.aiConfigs = [
{
id: "deepseek-default",
name: "DeepSeek",
provider: "deepseek",
apiKey: "test-key",
authMethod: "api-key",
endpoint: "https://api.deepseek.com",
model: "deepseek-chat",
apiStyle: "completions",
isDefault: true,
},
];
settings.activeModel = { configId: "deepseek-default", modelId: "deepseek-chat" };
});
expect(errors.map(String)).toEqual([]);
expect(container.querySelector(".ai-prompt-context-container")).not.toBeNull();
expect(container.querySelector("[data-ai-composer-actions]")).not.toBeNull();
expect(container.querySelector<HTMLButtonElement>(".ai-template-selector-trigger")?.getAttribute("aria-label")).toBeTruthy();
expect(container.querySelector<HTMLButtonElement>(".ai-skills-selector-trigger")?.getAttribute("aria-label")).toBe(i18n.global.t("ai.skillsEntry"));
const modeTrigger = container.querySelector<HTMLButtonElement>(".ai-mode-action-trigger");
expect(modeTrigger?.getAttribute("aria-label")).toBeTruthy();
expect(modeTrigger?.getAttribute("title")).toBe(modeTrigger?.getAttribute("aria-label"));
const modelTrigger = container.querySelector<HTMLButtonElement>(".ai-model-selector-trigger");
expect(modelTrigger?.getAttribute("aria-label")).toBe("deepseek-chat");
expect(modelTrigger?.getAttribute("title")).toBe("deepseek-chat");
});
it.each(["plugin", "etcd"] as const)("hides database and schema selectors for %s connections", async (dbType) => {
const { errors, container } = await mountPanel(true, { id: "connection", name: "Connection", db_type: dbType, plugin_id: dbType === "plugin" ? "sample.plugin" : undefined, host: "localhost", port: 22, username: "", password: "" });
expect(errors.map(String)).toEqual([]);