Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(ui): support direct keyboard typing and matching in SearchableSelect

lxk95586659553a68c
diff --git a/apps/desktop/src/components/ui/searchable-select/SearchableSelect.vue b/apps/desktop/src/components/ui/searchable-select/SearchableSelect.vue
index c55fc07e87..3fc42de682 100644
--- a/apps/desktop/src/components/ui/searchable-select/SearchableSelect.vue
+++ b/apps/desktop/src/components/ui/searchable-select/SearchableSelect.vue
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { computed, nextTick, ref, watch } from "vue";
-import type { HTMLAttributes } from "vue";
+import type { ComponentPublicInstance, HTMLAttributes } from "vue";
import { Check, ChevronDown, Search, X } from "@lucide/vue";
import { useI18n } from "vue-i18n";
import { Button } from "@/components/ui/button";
@@ -71,6 +71,7 @@ defineSlots<{
const open = ref(false);
const searchText = ref("");
const searchInput = ref<InstanceType<typeof Input>>();
+const triggerButton = ref<ComponentPublicInstance | HTMLElement>();
const listContainer = ref<HTMLDivElement>();
const listCard = ref<HTMLElement>();
const helpPanel = ref<{ element?: HTMLElement }>();
@@ -79,6 +80,78 @@ const activeHelpOption = ref<string>();
const helpPanelOffsetTop = ref(0);
const { t } = useI18n();
+let shouldFocusAdjacentOnClose = false;
+let tabDirection: 1 | -1 = 1;
+
+function getTriggerElement(): HTMLElement | undefined {
+ const target = triggerButton.value;
+ if (!target) return undefined;
+ if (target instanceof HTMLElement) return target;
+ return target.$el instanceof HTMLElement ? target.$el : undefined;
+}
+
+function getFocusableElements(): HTMLElement[] {
+ const selector =
+ 'button:not([disabled]):not([tabindex="-1"]), input:not([disabled]):not([tabindex="-1"]), select:not([disabled]):not([tabindex="-1"]), textarea:not([disabled]):not([tabindex="-1"]), a[href]:not([tabindex="-1"]), [contenteditable="true"]:not([tabindex="-1"]), [tabindex]:not([tabindex="-1"]):not([disabled])';
+ return Array.from(document.querySelectorAll<HTMLElement>(selector)).filter((el) => {
+ if (listCard.value?.contains(el)) return false;
+ if (el.hidden || el.getAttribute("aria-hidden") === "true") return false;
+ const style = window.getComputedStyle ? window.getComputedStyle(el) : el.style;
+ return style.display !== "none" && style.visibility !== "hidden";
+ });
+}
+
+function focusAdjacentElement(direction: 1 | -1) {
+ const trigger = getTriggerElement();
+ if (!trigger) return;
+ const elements = getFocusableElements();
+ const index = elements.indexOf(trigger);
+ if (index >= 0) {
+ const target = elements[index + direction];
+ if (target) {
+ target.focus();
+ return;
+ }
+ }
+ trigger.focus();
+}
+
+function handleCloseAutoFocus(event: Event) {
+ if (!shouldFocusAdjacentOnClose) return;
+ event.preventDefault();
+ const dir = tabDirection;
+ shouldFocusAdjacentOnClose = false;
+ focusAdjacentElement(dir);
+}
+
+function isPrintableCharacterKey(event: KeyboardEvent): boolean {
+ return event.key.length === 1 && !event.ctrlKey && !event.altKey && !event.metaKey && event.key !== " " && !event.isComposing && event.key !== "Process" && event.keyCode !== 229;
+}
+
+function handleTriggerKeydown(event: KeyboardEvent) {
+ if (props.disabled) return;
+ if (event.isComposing || event.key === "Process" || event.keyCode === 229) return;
+ if ((event.key === "Backspace" || event.key === "Delete") && props.clearable && props.modelValue) {
+ event.preventDefault();
+ emit("update:modelValue", "");
+ return;
+ }
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
+ event.preventDefault();
+ open.value = true;
+ return;
+ }
+ if (isPrintableCharacterKey(event)) {
+ event.preventDefault();
+ if (open.value) {
+ searchText.value += event.key;
+ } else {
+ searchText.value = event.key;
+ open.value = true;
+ }
+ }
+}
+
const selectedLabel = computed(() => {
if (!props.modelValue && !props.options.includes("")) return props.placeholder;
return props.displayName(props.modelValue);
@@ -127,18 +200,34 @@ watch(open, async (value) => {
searchText.value = "";
highlightIndex.value = -1;
activeHelpOption.value = undefined;
+ if (shouldFocusAdjacentOnClose) {
+ const dir = tabDirection;
+ shouldFocusAdjacentOnClose = false;
+ await nextTick();
+ focusAdjacentElement(dir);
+ }
return;
}
+ if (searchText.value) {
+ highlightIndex.value = optionCount() > 0 ? 0 : -1;
+ activateHelpForHighlightedOption();
+ } else {
+ highlightSelectedOption();
+ activateInitialHelpOption();
+ }
await nextTick();
const input = searchInput.value?.$el as HTMLInputElement | undefined;
input?.focus();
- highlightAndScrollSelectedOption();
- activateInitialHelpOption();
+ if (input) {
+ const len = input.value.length;
+ input.setSelectionRange?.(len, len);
+ }
+ void scrollHighlightedOptionIntoView();
});
watch(searchText, () => {
if (!open.value) return;
- highlightIndex.value = 0;
+ highlightIndex.value = optionCount() > 0 ? 0 : -1;
activeHelpOption.value = searchableSelectKeyboardTooltipOption(filteredOptions.value, 0, props.optionTooltip);
});
@@ -216,6 +305,7 @@ function optionCount() {
}
function handleKeydown(event: KeyboardEvent) {
+ if (event.isComposing || event.key === "Process" || event.keyCode === 229) return;
if (event.key === "ArrowDown") {
event.preventDefault();
const total = optionCount();
@@ -236,6 +326,19 @@ function handleKeydown(event: KeyboardEvent) {
} else {
selectCustomOption();
}
+ } else if (event.key === "Tab") {
+ event.preventDefault();
+ if (highlightIndex.value >= 0 && highlightIndex.value < optionCount()) {
+ if (highlightIndex.value < filteredOptions.value.length) {
+ selectOrClearOption(filteredOptions.value[highlightIndex.value]);
+ } else {
+ selectCustomOption();
+ }
+ } else {
+ open.value = false;
+ }
+ shouldFocusAdjacentOnClose = true;
+ tabDirection = event.shiftKey ? -1 : 1;
} else if (event.key === "Escape") {
open.value = false;
}
@@ -254,7 +357,7 @@ function handleKeydown(event: KeyboardEvent) {
which is also why the old in-trigger @pointerdown.stop never fired; @click.stop
keeps Reka's bubble-phase trigger onClick (onOpenToggle) from opening the dropdown.
-->
- <Button type="button" :variant="triggerVariant" :disabled="disabled" :title="selectedLabel" :class="cn('relative', triggerBaseClass, triggerClass)">
+ <Button ref="triggerButton" type="button" :variant="triggerVariant" :disabled="disabled" :title="selectedLabel" :class="cn('relative', triggerBaseClass, triggerClass)" @keydown="handleTriggerKeydown">
<slot name="trigger-label" :value="modelValue" :label="selectedLabel" :loading="loading">
<span class="truncate">{{ loading ? loadingText : selectedLabel }}</span>
</slot>
@@ -270,7 +373,7 @@ function handleKeydown(event: KeyboardEvent) {
</span>
</Button>
</PopoverTrigger>
- <PopoverContent :align="SEARCHABLE_SELECT_HELP_PANEL_ALIGN" :class="cn('w-auto max-w-[calc(100vw-1rem)] border-0 bg-transparent p-0 shadow-none ring-0', contentClass)" :style="contentStyle">
+ <PopoverContent :align="SEARCHABLE_SELECT_HELP_PANEL_ALIGN" :class="cn('w-auto max-w-[calc(100vw-1rem)] border-0 bg-transparent p-0 shadow-none ring-0', contentClass)" :style="contentStyle" @close-auto-focus="handleCloseAutoFocus">
<div class="flex min-w-0 flex-col gap-2 sm:flex-row sm:items-start">
<div ref="listCard" :class="cn('shrink-0 rounded-md border bg-popover p-1.5 shadow-md', listClass)">
<div class="relative rounded-md border bg-background">
@@ -287,6 +390,7 @@ function handleKeydown(event: KeyboardEvent) {
v-for="(option, index) in filteredOptions"
:key="option"
type="button"
+ tabindex="-1"
:title="optionTooltip(option) ? undefined : optionTitle(option)"
:class="
cn(
@@ -312,6 +416,7 @@ function handleKeydown(event: KeyboardEvent) {
<button
v-if="canSelectCustom"
type="button"
+ tabindex="-1"
:title="customOptionValue"
:class="
cn(
@@ -334,6 +439,7 @@ function handleKeydown(event: KeyboardEvent) {
<button
v-else-if="canSelectCustom"
type="button"
+ tabindex="-1"
:title="customOptionValue"
:class="
cn(
diff --git a/apps/desktop/src/components/ui/searchable-select/__tests__/SearchableSelect.trigger.spec.ts b/apps/desktop/src/components/ui/searchable-select/__tests__/SearchableSelect.trigger.spec.ts
index 08c972f429..2ad7268c76 100644
--- a/apps/desktop/src/components/ui/searchable-select/__tests__/SearchableSelect.trigger.spec.ts
+++ b/apps/desktop/src/components/ui/searchable-select/__tests__/SearchableSelect.trigger.spec.ts
@@ -84,4 +84,204 @@ describe("SearchableSelect trigger", () => {
expect(root.querySelector("button .invisible")).not.toBeNull();
});
+
+ it("opens popover and pre-fills search text when a printable character is pressed on trigger button", async () => {
+ const { root, emitted } = mountSelect({
+ options: ["int", "varchar", "bigint"],
+ modelValue: "int",
+ });
+
+ const trigger = root.querySelector("button")!;
+ const event = new KeyboardEvent("keydown", { key: "v", bubbles: true, cancelable: true });
+ trigger.dispatchEvent(event);
+
+ expect(event.defaultPrevented).toBe(true);
+ await nextTick();
+ expect(emitted.open).toEqual([true]);
+
+ const input = document.body.querySelector<HTMLInputElement>("input")!;
+ expect(input).not.toBeNull();
+ expect(input.value).toBe("v");
+ });
+
+ it("opens popover when ArrowDown or ArrowUp is pressed on trigger button", async () => {
+ const { root, emitted } = mountSelect();
+
+ const trigger = root.querySelector("button")!;
+ const event = new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true, cancelable: true });
+ trigger.dispatchEvent(event);
+
+ expect(event.defaultPrevented).toBe(true);
+ await nextTick();
+ expect(emitted.open).toEqual([true]);
+ });
+
+ it("clears value when Backspace or Delete is pressed on clearable trigger button", async () => {
+ const { root, emitted } = mountSelect({ clearable: true, modelValue: "Point" });
+
+ const trigger = root.querySelector("button")!;
+ const event = new KeyboardEvent("keydown", { key: "Backspace", bubbles: true, cancelable: true });
+ trigger.dispatchEvent(event);
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(emitted.modelValue).toEqual([""]);
+ expect(emitted.open).toEqual([]);
+ });
+
+ it("navigates and selects options with ArrowDown and Enter in search input", async () => {
+ const { root, emitted } = mountSelect({
+ options: ["varchar", "varbinary", "bigint"],
+ modelValue: "",
+ });
+
+ const trigger = root.querySelector("button")!;
+ trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "v", bubbles: true, cancelable: true }));
+
+ await nextTick();
+ const input = document.body.querySelector<HTMLInputElement>("input")!;
+ expect(input).not.toBeNull();
+
+ // ArrowDown moves highlight to "varbinary"
+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true, cancelable: true }));
+ await nextTick();
+
+ // Enter selects "varbinary"
+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
+ await nextTick();
+
+ expect(emitted.modelValue).toContain("varbinary");
+ expect(emitted.open).toContain(false);
+ });
+
+ it("selects highlighted option and closes when Tab is pressed in search input", async () => {
+ const { root, emitted } = mountSelect({
+ options: ["varchar", "varbinary", "bigint"],
+ modelValue: "",
+ });
+
+ const trigger = root.querySelector("button")!;
+ trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "v", bubbles: true, cancelable: true }));
+
+ await nextTick();
+ const input = document.body.querySelector<HTMLInputElement>("input")!;
+ expect(input).not.toBeNull();
+
+ // Tab selects first match ("varchar") and closes
+ const tabEvent = new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true });
+ input.dispatchEvent(tabEvent);
+ await nextTick();
+
+ expect(tabEvent.defaultPrevented).toBe(true);
+ expect(emitted.modelValue).toContain("varchar");
+ expect(emitted.open).toContain(false);
+ });
+
+ it("does not intercept Tab while an IME composition is active in search input", async () => {
+ const { root, emitted } = mountSelect({
+ options: ["varchar", "bigint"],
+ modelValue: "",
+ });
+
+ const trigger = root.querySelector("button")!;
+ trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "v", bubbles: true, cancelable: true }));
+
+ await nextTick();
+ const input = document.body.querySelector<HTMLInputElement>("input")!;
+ expect(input).not.toBeNull();
+
+ const composingTab = new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true });
+ Object.defineProperty(composingTab, "isComposing", { value: true });
+ input.dispatchEvent(composingTab);
+ await nextTick();
+
+ // Composition must survive: no selection, no close, focus stays in the search input.
+ expect(emitted.modelValue).toEqual([]);
+ expect(emitted.open).not.toContain(false);
+ expect(document.activeElement).toBe(input);
+ });
+
+ it("marks list option buttons with tabindex=-1 to prevent tab trapping", async () => {
+ const { root } = mountSelect({
+ options: ["int", "varchar"],
+ });
+
+ const trigger = root.querySelector("button")!;
+ trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true, cancelable: true }));
+ await nextTick();
+
+ const optionButtons = document.body.querySelectorAll(".dbx-searchable-select-list button");
+ expect(optionButtons.length).toBeGreaterThan(0);
+ for (const btn of optionButtons) {
+ expect(btn.getAttribute("tabindex")).toBe("-1");
+ }
+ });
+
+ it("does not open popover on keydown when trigger is disabled", async () => {
+ const { root, emitted } = mountSelect({ disabled: true });
+
+ const trigger = root.querySelector("button")!;
+ const event = new KeyboardEvent("keydown", { key: "v", bubbles: true, cancelable: true });
+ trigger.dispatchEvent(event);
+
+ await nextTick();
+ expect(event.defaultPrevented).toBe(false);
+ expect(emitted.open).toEqual([]);
+ });
+
+ it("accumulates rapid keystrokes on the trigger before input receives focus", async () => {
+ const { root } = mountSelect({
+ options: ["int", "varchar"],
+ modelValue: "",
+ });
+
+ const trigger = root.querySelector("button")!;
+ trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "v", bubbles: true, cancelable: true }));
+ trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "a", bubbles: true, cancelable: true }));
+
+ await nextTick();
+ const input = document.body.querySelector<HTMLInputElement>("input")!;
+ expect(input.value).toBe("va");
+ });
+
+ it("focuses adjacent element when Tab or Shift+Tab is pressed in search input", async () => {
+ const root = document.createElement("div");
+ const prevInput = document.createElement("input");
+ prevInput.id = "prev-input";
+ const nextInput = document.createElement("input");
+ nextInput.id = "next-input";
+ root.append(prevInput);
+ const selectContainer = document.createElement("div");
+ root.append(selectContainer);
+ root.append(nextInput);
+ document.body.append(root);
+
+ const emitted = { modelValue: [] as unknown[], open: [] as unknown[] };
+ const app = createApp(SearchableSelect, {
+ modelValue: "",
+ options: ["int", "varchar"],
+ placeholder: "type",
+ searchPlaceholder: "search",
+ emptyText: "empty",
+ "onUpdate:modelValue": (v: unknown) => emitted.modelValue.push(v),
+ "onUpdate:open": (v: unknown) => emitted.open.push(v),
+ });
+ mountedApps.push(app);
+ app.mount(selectContainer);
+
+ const trigger = selectContainer.querySelector("button")!;
+ trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "i", bubbles: true, cancelable: true }));
+ await nextTick();
+
+ const searchInput = document.body.querySelector<HTMLInputElement>("input[data-slot='input']")!;
+ expect(searchInput).not.toBeNull();
+
+ const tabEvent = new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true });
+ searchInput.dispatchEvent(tabEvent);
+ await nextTick();
+ await nextTick();
+
+ expect(tabEvent.defaultPrevented).toBe(true);
+ expect(emitted.modelValue).toEqual(["int"]);
+ expect(document.activeElement).toBe(nextInput);
+ });
});