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(sidebar): add foreground table-name match mode selector

Abeautifulsnowf84a1fa96550
diff --git a/apps/desktop/src/components/sidebar/ConnectionTree.vue b/apps/desktop/src/components/sidebar/ConnectionTree.vue
index fbf09d2d9a..9c2fda845b 100644
--- a/apps/desktop/src/components/sidebar/ConnectionTree.vue
+++ b/apps/desktop/src/components/sidebar/ConnectionTree.vue
@@ -24,7 +24,7 @@ import {
type SidebarRegexScopeIdentity,
localTableSearchParentTypes,
} from "@/lib/sidebar/sidebarSearchTree";
-import { createSidebarLabelMatcher } from "@/lib/sidebar/sidebarSearch";
+import { createSidebarLabelMatcher, type SidebarSearchMatchMode } from "@/lib/sidebar/sidebarSearch";
import { firstSidebarSearchMatchDataNode, hasActiveSidebarSearch } from "@/lib/sidebar/sidebarSearchEnter";
import { collectSidebarRegexIndexScopes } from "@/lib/sidebar/sidebarRegexSearchIndex";
import { collectSidebarGlobalSearchIndexes, sidebarIndexedObjectGroupTypes } from "@/lib/sidebar/sidebarGlobalSearchIndex";
@@ -73,6 +73,7 @@ import ActiveConnectionFilterButton from "./ActiveConnectionFilterButton.vue";
import SidebarListOptionsIcon from "./SidebarListOptionsIcon.vue";
import SidebarLocateButton from "./SidebarLocateButton.vue";
import SidebarRegexToggleButton from "./SidebarRegexToggleButton.vue";
+import SidebarSearchMatchModeSelect from "./SidebarSearchMatchModeSelect.vue";
import SidebarTreeRuntimeHost from "./SidebarTreeRuntimeHost.vue";
import SidebarTreeItemDialogs from "./SidebarTreeItemDialogs.vue";
import SidebarTableVGroupDialog from "./SidebarTableVGroupDialog.vue";
@@ -118,6 +119,14 @@ const { toast } = useToast();
const searchQuery = ref("");
const deferredSearchQuery = ref("");
const regexMode = ref(false);
+// Session-scoped foreground match mode (#13505). Deliberately not persisted:
+// the default stays `fuzzy`, i.e. today's behavior, and the choice resets with
+// the window. Regex mode keeps its own semantics and disables this selector.
+// Scope: the top search input only (tree search + global table index). The
+// per-database inline search boxes keep their own local/remote behavior; the
+// remote path is server-filtered, so sharing this mode would make local and
+// remote results diverge.
+const searchMatchMode = ref<SidebarSearchMatchMode>("fuzzy");
store.sidebarSearchQuery = "";
const showConnectedConnectionsOnly = ref(false);
const isDisconnectingAllActiveConnections = ref(false);
@@ -647,7 +656,7 @@ async function loadGlobalTableSearchIndexes(shouldCancel: () => boolean, onProgr
function filterGloballyIndexedTables(nodes: TreeNode[]): TreeNode[] {
if (!deferredSearchQuery.value) return nodes;
- const matcher = createSidebarLabelMatcher(deferredSearchQuery.value, { regexMode: regexMode.value });
+ const matcher = createSidebarLabelMatcher(deferredSearchQuery.value, { regexMode: regexMode.value, matchMode: searchMatchMode.value });
const matchingScopes = globalTableSearchScopes.value.map((scope) => ({ ...scope, entries: scope.entries.filter((entry) => !!matcher(entry.name) || !!matcher(entry.comment || "")) })).filter((scope) => scope.entries.length > 0);
return mergeSidebarRegexIndexScopes(nodes, matchingScopes);
}
@@ -724,6 +733,7 @@ const filteredNodes = computed(() => {
const q = deferredSearchQuery.value;
nodes = filterSidebarTree(nodes, q, searchCollapsedIds.value, searchableNodeTypes.value, {
regexMode: regexMode.value,
+ matchMode: searchMatchMode.value,
resolveLabel: (node) => (node.type === "nacos-access-control" ? t("nacos.accessControlSidebarLabel") : node.label),
});
if (q && !regexMode.value) {
@@ -2843,7 +2853,7 @@ defineExpose({
autocapitalize="off"
autocorrect="off"
spellcheck="false"
- class="w-full h-6 pl-7 pr-[4.75rem] text-xs rounded border bg-background focus:outline-none focus:ring-1 focus:ring-ring"
+ class="w-full h-6 pl-7 pr-[6.25rem] text-xs rounded border bg-background focus:outline-none focus:ring-1 focus:ring-ring"
:class="regexMode && compileSearchRegex(searchQuery).invalid ? 'border-destructive focus:ring-destructive' : 'border-border'"
:aria-invalid="regexMode && compileSearchRegex(searchQuery).invalid ? 'true' : 'false'"
:placeholder="t('grid.search')"
@@ -2856,6 +2866,8 @@ defineExpose({
<LightTooltip :text="t('sidebar.regexSearchTooltip')" side="top" :delay="300">
<SidebarRegexToggleButton :label="t('sidebar.regexSearch')" :pressed="regexMode" :invalid="regexMode && compileSearchRegex(searchQuery).invalid" @toggle="regexMode = !regexMode" />
</LightTooltip>
+ <!-- Regex has its own semantics, so the plain-text match mode is disabled while it is on. -->
+ <SidebarSearchMatchModeSelect v-model="searchMatchMode" :disabled="regexMode" />
<LightTooltip :text="t('sidebar.globalLocalSearchTooltip')" side="top" :delay="300">
<Switch size="sm" :model-value="settingsStore.editorSettings.sidebarGlobalSearchLocal" :disabled="regexMode" :aria-label="t('sidebar.globalLocalSearch')" @update:model-value="settingsStore.updateEditorSettings({ sidebarGlobalSearchLocal: Boolean($event) })" />
</LightTooltip>
diff --git a/apps/desktop/src/components/sidebar/SidebarSearchMatchModeSelect.vue b/apps/desktop/src/components/sidebar/SidebarSearchMatchModeSelect.vue
new file mode 100644
index 0000000000..4a6fc636f2
--- /dev/null
+++ b/apps/desktop/src/components/sidebar/SidebarSearchMatchModeSelect.vue
@@ -0,0 +1,82 @@
+<script setup lang="ts">
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { BetweenHorizontalStart, TextSearch, Wand2 } from "@lucide/vue";
+import LightDropdownMenu, { type LightDropdownMenuItem } from "@/components/ui/LightDropdownMenu.vue";
+import LightTooltip from "@/components/ui/LightTooltip.vue";
+import type { SidebarSearchMatchMode } from "@/lib/sidebar/sidebarSearch";
+
+const props = defineProps<{
+ modelValue: SidebarSearchMatchMode;
+ disabled?: boolean;
+}>();
+
+const emit = defineEmits<{
+ "update:modelValue": [mode: SidebarSearchMatchMode];
+}>();
+
+const { t } = useI18n();
+
+const MODE_ICONS = {
+ fuzzy: Wand2,
+ contains: TextSearch,
+ edges: BetweenHorizontalStart,
+} as const;
+
+const MODE_LABEL_KEYS = {
+ fuzzy: "sidebar.searchMatchModeFuzzy",
+ contains: "sidebar.searchMatchModeContains",
+ edges: "sidebar.searchMatchModeEdges",
+} as const;
+
+const modes: SidebarSearchMatchMode[] = ["fuzzy", "contains", "edges"];
+
+const items = computed<LightDropdownMenuItem[]>(() =>
+ modes.map((mode) => ({
+ label: t(MODE_LABEL_KEYS[mode]),
+ value: mode,
+ icon: MODE_ICONS[mode],
+ // `checked` binds the checkmark to the prop instead of the dropdown's own
+ // single-value bookkeeping, so a parent reset is reflected immediately.
+ checked: mode === props.modelValue,
+ // One-of-three choice: announce it as a radio option with its state.
+ role: "menuitemradio",
+ })),
+);
+
+const activeIcon = computed(() => MODE_ICONS[props.modelValue]);
+const activeModeLabel = computed(() => t(MODE_LABEL_KEYS[props.modelValue]));
+</script>
+
+<template>
+ <LightDropdownMenu
+ :items="items"
+ align="end"
+ :match-trigger-width="false"
+ :disabled="disabled"
+ content-class="w-max min-w-0"
+ selected-item-class="bg-primary/10 text-primary"
+ selected-check-class="text-primary"
+ item-icon-class="h-3.5 w-3.5"
+ @select="(mode: string) => emit('update:modelValue', mode as SidebarSearchMatchMode)"
+ >
+ <template #trigger="{ open, toggle }">
+ <LightTooltip :text="`${activeModeLabel} — ${t('sidebar.searchMatchModeTooltip')}`" side="top" :delay="300">
+ <button
+ type="button"
+ data-sidebar-search-match-mode-trigger
+ :data-sidebar-search-match-mode="modelValue"
+ class="relative flex h-5 min-w-5 shrink-0 items-center justify-center rounded-sm px-0.5 text-muted-foreground hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50"
+ :class="{ 'bg-accent text-foreground': open }"
+ :aria-label="`${t('sidebar.searchMatchMode')}: ${activeModeLabel}`"
+ aria-haspopup="menu"
+ :aria-expanded="open"
+ :disabled="disabled"
+ @click.stop="toggle"
+ >
+ <component :is="activeIcon" class="h-3.5 w-3.5" />
+ </button>
+ </LightTooltip>
+ </template>
+ </LightDropdownMenu>
+</template>
diff --git a/apps/desktop/src/components/sidebar/__tests__/SidebarSearchMatchModeSelect.spec.ts b/apps/desktop/src/components/sidebar/__tests__/SidebarSearchMatchModeSelect.spec.ts
new file mode 100644
index 0000000000..cd2e6c5841
--- /dev/null
+++ b/apps/desktop/src/components/sidebar/__tests__/SidebarSearchMatchModeSelect.spec.ts
@@ -0,0 +1,139 @@
+// @vitest-environment happy-dom
+
+import { createApp, defineComponent, h, nextTick, reactive, type App } from "vue";
+import { createI18n } from "vue-i18n";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import SidebarSearchMatchModeSelect from "../SidebarSearchMatchModeSelect.vue";
+import type { SidebarSearchMatchMode } from "@/lib/sidebar/sidebarSearch";
+
+const messages = {
+ sidebar: {
+ searchMatchMode: "Match mode",
+ searchMatchModeFuzzy: "Fuzzy",
+ searchMatchModeContains: "Contains",
+ searchMatchModeEdges: "Edges",
+ searchMatchModeTooltip: "How sidebar search matches names.",
+ },
+};
+
+const mountedApps: App[] = [];
+
+async function mount(initial: SidebarSearchMatchMode, state?: { disabled: boolean; mode: SidebarSearchMatchMode }) {
+ const container = document.createElement("div");
+ document.body.append(container);
+ const model = reactive({ value: initial, disabled: state?.disabled ?? false });
+ const onUpdate = vi.fn();
+ const app = createApp(
+ defineComponent({
+ setup: () => () =>
+ h(SidebarSearchMatchModeSelect, {
+ modelValue: model.value,
+ disabled: model.disabled,
+ "onUpdate:modelValue": (mode: SidebarSearchMatchMode) => {
+ model.value = mode;
+ onUpdate(mode);
+ },
+ }),
+ }),
+ );
+ app.use(createI18n({ legacy: false, locale: "en", missingWarn: false, fallbackWarn: false, messages: { en: messages } }));
+ mountedApps.push(app);
+ app.mount(container);
+ await nextTick();
+ if (state) state.mode = model.value;
+ return { container, onUpdate, model };
+}
+
+function trigger(container: HTMLElement): HTMLButtonElement {
+ const element = container.querySelector("[data-sidebar-search-match-mode-trigger]");
+ if (!(element instanceof HTMLButtonElement)) throw new Error("Match mode trigger was not rendered");
+ return element;
+}
+
+function menuItems(): HTMLButtonElement[] {
+ return [...document.body.querySelectorAll<HTMLButtonElement>('[role="menu"] [role="menuitemradio"]')];
+}
+
+function checkedItemLabel(): string | undefined {
+ return menuItems()
+ .find((item) => item.getAttribute("aria-checked") === "true")
+ ?.textContent?.trim();
+}
+
+afterEach(() => {
+ for (const app of mountedApps.splice(0)) app.unmount();
+ document.body.innerHTML = "";
+});
+
+describe("SidebarSearchMatchModeSelect", () => {
+ it("renders the active mode on the trigger with menu semantics", async () => {
+ const { container } = await mount("fuzzy");
+ const button = trigger(container);
+
+ expect(button.getAttribute("data-sidebar-search-match-mode")).toBe("fuzzy");
+ expect(button.getAttribute("aria-haspopup")).toBe("menu");
+ expect(button.getAttribute("aria-expanded")).toBe("false");
+ expect(button.getAttribute("aria-label")).toBe("Match mode: Fuzzy");
+ expect(button.disabled).toBe(false);
+ expect(container.querySelector("[data-sidebar-search-match-mode-trigger] .lucide-wand-2")).not.toBeNull();
+ });
+
+ it("lists all three modes and checks the active one", async () => {
+ const { container } = await mount("contains");
+ trigger(container).click();
+ await nextTick();
+
+ expect(trigger(container).getAttribute("aria-expanded")).toBe("true");
+ expect(menuItems().map((item) => item.textContent?.trim())).toEqual(["Fuzzy", "Contains", "Edges"]);
+ expect(checkedItemLabel()).toBe("Contains");
+ // Radio semantics: the single-select group reports its state to assistive tech.
+ expect(menuItems().map((item) => item.getAttribute("aria-checked"))).toEqual(["false", "true", "false"]);
+ });
+
+ it("emits the picked mode once and reflects it back on the trigger", async () => {
+ const { container, onUpdate } = await mount("fuzzy");
+ trigger(container).click();
+ await nextTick();
+
+ const edges = menuItems().find((item) => item.textContent?.trim() === "Edges");
+ expect(edges).toBeTruthy();
+ edges!.click();
+ await nextTick();
+
+ expect(onUpdate).toHaveBeenCalledTimes(1);
+ expect(onUpdate).toHaveBeenCalledWith("edges");
+ expect(trigger(container).getAttribute("data-sidebar-search-match-mode")).toBe("edges");
+ expect(trigger(container).getAttribute("aria-label")).toBe("Match mode: Edges");
+ // Single-select dropdown closes after a pick.
+ expect(menuItems()).toHaveLength(0);
+ });
+
+ it("moves focus between the radio options with the arrow keys", async () => {
+ const { container } = await mount("fuzzy");
+ trigger(container).click();
+ await nextTick();
+
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
+ await nextTick();
+ expect(document.activeElement).toBe(menuItems()[0]);
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
+ await nextTick();
+ expect(document.activeElement).toBe(menuItems()[1]);
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
+ await nextTick();
+ expect(menuItems()).toHaveLength(0);
+ });
+
+ it("disables the trigger and stays closed while regex mode owns the search", async () => {
+ const { container } = await mount("fuzzy", { disabled: true, mode: "fuzzy" });
+ const button = trigger(container);
+
+ expect(button.disabled).toBe(true);
+ expect(button.getAttribute("aria-label")).toBe("Match mode: Fuzzy");
+ button.click();
+ await nextTick();
+ expect(button.getAttribute("aria-expanded")).toBe("false");
+ expect(menuItems()).toHaveLength(0);
+ expect(container.querySelector("[data-sidebar-search-match-mode-trigger]")?.className).toContain("disabled:opacity-50");
+ });
+});
diff --git a/apps/desktop/src/components/ui/LightDropdownMenu.vue b/apps/desktop/src/components/ui/LightDropdownMenu.vue
index b8e4bb32cd..dcb6acb38c 100644
--- a/apps/desktop/src/components/ui/LightDropdownMenu.vue
+++ b/apps/desktop/src/components/ui/LightDropdownMenu.vue
@@ -16,6 +16,12 @@ export interface LightDropdownMenuItem {
separatorBefore?: boolean;
destructive?: boolean;
checked?: boolean;
+ /**
+ * Single-select menus can opt into radio semantics so assistive tech announces
+ * the active option. Defaults to a plain `menuitem`, which keeps every
+ * existing caller's markup unchanged.
+ */
+ role?: "menuitem" | "menuitemradio" | "menuitemcheckbox";
closeOnSelect?: boolean;
onSelect?: () => void;
}
@@ -194,7 +200,7 @@ function onKeydown(event: KeyboardEvent) {
}
function menuItems() {
- return Array.from(menuRef.value?.querySelectorAll<HTMLButtonElement>("[role='menuitem']:not(:disabled)") ?? []);
+ return Array.from(menuRef.value?.querySelectorAll<HTMLButtonElement>("[role='menuitem']:not(:disabled), [role='menuitemradio']:not(:disabled), [role='menuitemcheckbox']:not(:disabled)") ?? []);
}
function focusMenuItem(direction: 1 | -1) {
@@ -279,7 +285,8 @@ watch(
"
:disabled="item.disabled"
:title="item.title"
- role="menuitem"
+ :role="item.role ?? 'menuitem'"
+ :aria-checked="item.role === 'menuitemradio' || item.role === 'menuitemcheckbox' ? itemIsSelected(item) : undefined"
@click="selectItem(item)"
>
<Check v-if="checkPosition === 'left'" class="h-3 w-3 shrink-0" :class="itemIsSelected(item) ? selectedCheckClass : 'opacity-0'" />
diff --git a/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts b/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts
index bab9586fb1..02c4f79bea 100644
--- a/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts
+++ b/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts
@@ -140,6 +140,7 @@ const FEATURE_MESSAGES: FeatureMessages[] = [
translated: true,
},
{ feature: "sidebar search skip hint", keys: ["sidebar.searchConnectionSkipped"] },
+ { feature: "sidebar search match mode (#13505)", keys: under("sidebar", ["searchMatchMode", "searchMatchModeFuzzy", "searchMatchModeContains", "searchMatchModeEdges", "searchMatchModeTooltip"]), translated: true },
{ feature: "PostgreSQL legacy TLS", keys: ["connection.postgresLegacyTls", "connection.postgresLegacyTlsHint"] },
{ feature: "settings search sections", keys: ["settings.syncWebDavWebDescription", "settings.performanceSection"] },
{ feature: "local backup selection", keys: ["settings.localBackupSecretsPassphraseRequiredHint", "settings.localBackupPathLabel", "settings.localBackupPathUnset", "settings.localBackupChoosePath", "settings.localBackupPathRequired"], translated: true },
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 2de375656b..9feceee61f 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -510,6 +510,11 @@ export default withEnglishFallback({
globalLocalSearchTooltip: "Uzaq sorğular göndərmədən yüklənmiş obyektlərdə və keşlənmiş cədvəl indekslərində axtarın. Çatışmayan indeksləri yaratmaq və digər obyektləri uzaqdan axtarmaq üçün deaktiv edin. Metaverilənləri yeniləmək üçün yeniləmə əməliyyatından istifadə edin.",
regexSearch: "Müntəzəm ifadə ilə axtarış",
regexSearchTooltip: "Yan paneldəki adları, şərhləri və ləqəbləri JavaScript müntəzəm ifadələri ilə uyğunlaşdırın.",
+ searchMatchMode: "Uyğunluq rejimi",
+ searchMatchModeFuzzy: "Qeyri-dəqiq",
+ searchMatchModeContains: "İçərir",
+ searchMatchModeEdges: "Kənarlar",
+ searchMatchModeTooltip: "Yan panel axtarışının adları, şərhləri və ləqəbləri necə uyğunlaşdırdığı: qeyri-dəqiq simvolların sıra ilə görünməsinə icazə verir, içərir davamlı fraqment tələb edir, kənarlar mətni yalnız adın əvvəlində və ya sonunda qəbul edir.",
clearFilter: "Süzgəci təmizlə",
locateTargetNotFound: "Element yan paneldə mövcud deyil. O, silinmiş və ya gizlədilmiş ola bilər.",
locateSqlFile: "SQL fayl siyahısında tap",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index b7291dd37b..3cabfc6566 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -1402,6 +1402,11 @@ export default {
globalLocalSearchTooltip: "Search loaded objects and cached table indexes without remote requests. Turn off to build missing indexes and search other objects remotely. Use Refresh to update metadata.",
regexSearch: "Regex search",
regexSearchTooltip: "Match sidebar names, comments, and aliases with JavaScript regular expressions.",
+ searchMatchMode: "Match mode",
+ searchMatchModeFuzzy: "Fuzzy",
+ searchMatchModeContains: "Contains",
+ searchMatchModeEdges: "Edges",
+ searchMatchModeTooltip: "How sidebar search matches names, comments, and aliases: fuzzy allows characters in order, contains requires a contiguous fragment, edges requires the text at the start or the end.",
clearFilter: "Clear filter",
locateTargetNotFound: "The item is not available in the sidebar. It may have been removed or hidden.",
locateSqlFile: "Locate in SQL file list",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index a4d665a01b..62360df422 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -1201,6 +1201,11 @@ export default withEnglishFallback({
globalLocalSearchTooltip: "Busca objetos cargados e índices de tablas en caché sin solicitudes remotas. Desactívalo para crear los índices faltantes y buscar otros objetos de forma remota. Usa Actualizar para actualizar los metadatos.",
regexSearch: "Búsqueda con regex",
regexSearchTooltip: "Coincide con nombres, comentarios y alias mediante expresiones regulares de JavaScript.",
+ searchMatchMode: "Modo de coincidencia",
+ searchMatchModeFuzzy: "Difuso",
+ searchMatchModeContains: "Contiene",
+ searchMatchModeEdges: "Extremos",
+ searchMatchModeTooltip: "Cómo coincide la búsqueda lateral con nombres, comentarios y alias: difuso permite caracteres en orden, contiene exige un fragmento contiguo y extremos exige el texto al principio o al final.",
clearFilter: "Limpiar filtro",
locateTargetNotFound: "El elemento no está disponible en la barra lateral. Puede que se haya eliminado u ocultado.",
locateSqlFile: "Localizar en la lista de archivos SQL",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index f288894127..d6e208b27f 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -715,6 +715,11 @@ export default withEnglishFallback({
globalLocalSearchTooltip: "Cari objek yang sudah dimuat dan indeks tabel tersimpan tanpa permintaan jarak jauh. Nonaktifkan untuk membuat indeks yang belum tersedia dan mencari objek lain di server. Gunakan Segarkan untuk memperbarui metadata.",
regexSearch: "Pencarian regex",
regexSearchTooltip: "Cocokkan nama, komentar, dan alias di bilah sisi dengan ekspresi reguler JavaScript.",
+ searchMatchMode: "Mode pencocokan",
+ searchMatchModeFuzzy: "Samar",
+ searchMatchModeContains: "Mengandung",
+ searchMatchModeEdges: "Ujung",
+ searchMatchModeTooltip: "Cara pencarian bilah sisi mencocokkan nama, komentar, dan alias: samar mengizinkan karakter berurutan, mengandung memerlukan fragmen bersebelahan, ujung hanya mencocokkan teks di awal atau akhir nama.",
clearFilter: "Bersihkan filter",
locateTargetNotFound: "Item tidak tersedia di bilah sisi. Item mungkin telah dihapus atau disembunyikan.",
locateSqlFile: "Temukan dalam daftar file SQL",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index f071247810..ee1ec36165 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -1189,6 +1189,11 @@ export default withEnglishFallback({
globalLocalSearchTooltip: "Cerca oggetti caricati e indici delle tabelle in cache senza richieste remote. Disattiva per creare gli indici mancanti e cercare altri oggetti in remoto. Usa Aggiorna per aggiornare i metadati.",
regexSearch: "Ricerca regex",
regexSearchTooltip: "Trova nomi, commenti e alias con espressioni regolari JavaScript.",
+ searchMatchMode: "Modalità di corrispondenza",
+ searchMatchModeFuzzy: "Approssimativa",
+ searchMatchModeContains: "Contiene",
+ searchMatchModeEdges: "Estremi",
+ searchMatchModeTooltip: "Come la ricerca laterale confronta nomi, commenti e alias: fuzzy consente caratteri in ordine, contiene richiede un frammento contiguo, estremi richiede il testo all'inizio o alla fine.",
clearFilter: "Cancella filtro",
locateTargetNotFound: "L’elemento non è disponibile nella barra laterale. Potrebbe essere stato rimosso o nascosto.",
locateSqlFile: "Individua nell’elenco dei file SQL",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index a60dec64e5..5612427024 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -1190,6 +1190,11 @@ export default withEnglishFallback({
globalLocalSearchTooltip: "リモート要求を行わずに読み込み済みオブジェクトとキャッシュされたテーブルインデックスを検索します。オフにすると不足しているインデックスを作成し、他のオブジェクトをリモートで検索します。メタデータを更新するには更新を使用してください。",
regexSearch: "正規表現検索",
regexSearchTooltip: "JavaScript 正規表現でサイドバーの名前、コメント、エイリアスを照合します。",
+ searchMatchMode: "一致モード",
+ searchMatchModeFuzzy: "あいまい",
+ searchMatchModeContains: "含む",
+ searchMatchModeEdges: "先頭・末尾",
+ searchMatchModeTooltip: "サイドバー検索が名前、コメント、エイリアスを照合する方法: あいまいは文字が順に現れれば一致、含むは連続した文字列が必要、先頭・末尾は名前の先頭か末尾にある場合のみ一致します。",
clearFilter: "フィルターをクリア",
locateTargetNotFound: "サイドバーに該当する項目が見つかりません。削除または非表示にされている可能性があります。",
locateSqlFile: "SQL ファイル一覧で表示",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 7a6408e6be..ad712488fa 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -1196,6 +1196,11 @@ export default withEnglishFallback({
globalLocalSearchTooltip: "원격 요청 없이 로드된 객체 및 캐시된 테이블 인덱스를 검색합니다. 누락된 인덱스를 생성하고 다른 객체를 원격으로 검색하려면 끄세요. 메타데이터를 업데이트하려면 새로 고침을 사용하세요.",
regexSearch: "정규식 검색",
regexSearchTooltip: "JavaScript 정규식으로 사이드바 이름, 주석, 별칭을 검색합니다.",
+ searchMatchMode: "일치 모드",
+ searchMatchModeFuzzy: "유사",
+ searchMatchModeContains: "포함",
+ searchMatchModeEdges: "앞뒤",
+ searchMatchModeTooltip: "사이드바 검색이 이름, 주석, 별칭을 일치시키는 방식: 유사는 문자가 순서대로 나타나면 일치, 포함은 연속된 문자열이 필요, 앞뒤는 이름의 시작이나 끝에 있는 경우만 일치합니다.",
clearFilter: "필터 지우기",
locateTargetNotFound: "사이드바에서 해당 항목을 찾을 수 없습니다. 삭제되었거나 숨겨져 있을 수 있습니다.",
locateSqlFile: "SQL 파일 목록에서 찾기",
diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.ts
index 95b0a50daf..98630aa021 100644
--- a/apps/desktop/src/i18n/locales/pl.ts
+++ b/apps/desktop/src/i18n/locales/pl.ts
@@ -774,6 +774,11 @@ export default withEnglishFallback({
globalLocalSearchTooltip: "Przeszukuj wczytane obiekty i indeksy tabel w pamięci podręcznej bez zapytań zdalnych. Wyłącz, aby utworzyć brakujące indeksy i szukać innych obiektów zdalnie. Użyj Odśwież, aby zaktualizować metadane.",
regexSearch: "Wyszukiwanie wyrażeniem regularnym",
regexSearchTooltip: "Dopasowuj nazwy, komentarze i aliasy w panelu bocznym przy użyciu wyrażeń regularnych JavaScript.",
+ searchMatchMode: "Tryb dopasowania",
+ searchMatchModeFuzzy: "Przybliżony",
+ searchMatchModeContains: "Zawiera",
+ searchMatchModeEdges: "Krawędzie",
+ searchMatchModeTooltip: "Jak wyszukiwanie w panelu bocznym dopasowuje nazwy, komentarze i aliasy: przybliżony pozwala na znaki w kolejności, zawiera wymaga ciągłego fragmentu, krawędzie wymaga tekstu na początku lub końcu nazwy.",
clearFilter: "Wyczyść filtr",
locateTargetNotFound: "Pozycja nie jest dostępna w panelu bocznym. Mogła zostać usunięta lub ukryta.",
locateSqlFile: "Znajdź na liście plików SQL",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index d9b4d952ce..a19a309baf 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -1190,6 +1190,11 @@ export default withEnglishFallback({
globalLocalSearchTooltip: "Pesquisa objetos carregados e índices de tabelas em cache sem solicitações remotas. Desative para criar índices ausentes e pesquisar outros objetos remotamente. Use Atualizar para atualizar os metadatos.",
regexSearch: "Busca por regex",
regexSearchTooltip: "Correspondência de nomes, comentários e aliases com expressões regulares JavaScript.",
+ searchMatchMode: "Modo de correspondência",
+ searchMatchModeFuzzy: "Difuso",
+ searchMatchModeContains: "Contém",
+ searchMatchModeEdges: "Extremidades",
+ searchMatchModeTooltip: "Como a busca lateral corresponde a nomes, comentários e aliases: difuso permite caracteres em ordem, contém exige um trecho contíguo e extremidades exige o texto no início ou no fim.",
clearFilter: "Limpar filtro",
locateTargetNotFound: "O item não está disponível na barra lateral. Ele pode ter sido removido ou ocultado.",
locateSqlFile: "Localizar na lista de arquivos SQL",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index d93f7bb941..404e652d09 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -1170,6 +1170,11 @@ export default withEnglishFallback({
globalLocalSearchTooltip: "Поиск по загруженным объектам и кэшированным индексам таблиц без удалённых запросов. Отключите для построения недостающих индексов и удалённого поиска других объектов. Используйте обновление для обновления метаданных.",
regexSearch: "Поиск по регулярному выражению",
regexSearchTooltip: "Сопоставлять имена, комментарии и псевдонимы в боковой панели с помощью регулярных выражений JavaScript.",
+ searchMatchMode: "Режим сопоставления",
+ searchMatchModeFuzzy: "Нечёткий",
+ searchMatchModeContains: "Содержит",
+ searchMatchModeEdges: "Края",
+ searchMatchModeTooltip: "Как поиск на боковой панели сопоставляет имена, комментарии и псевдонимы: нечёткий допускает символы по порядку, содержит требует непрерывный фрагмент, края требует текст в начале или в конце имени.",
clearFilter: "Очистить фильтр",
locateTargetNotFound: "Элемент недоступен на боковой панели. Возможно, он был удалён или скрыт.",
locateSqlFile: "Найти в списке SQL-файлов",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index 4d8e8d0ae4..222f52413c 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -1270,6 +1270,11 @@ export default withEnglishFallback({
globalLocalSearchTooltip: "ค้นหาออบเจ็กต์ที่โหลดแล้วและ Index ตารางในแคชโดยไม่ส่ง Request ระยะไกล ปิดเพื่อสร้าง Index ที่ขาดหายไปและค้นหาออบเจ็กต์อื่นจากระยะไกล ใช้รีเฟรชเพื่ออัปเดต Metadata",
regexSearch: "การค้นหา Regex",
regexSearchTooltip: "จับคู่ชื่อ คอมเมนต์ และ Alias ในแถบด้านข้างด้วย Regular Expression ของ JavaScript",
+ searchMatchMode: "โหมดการจับคู่",
+ searchMatchModeFuzzy: "คล้ายกัน",
+ searchMatchModeContains: "มีข้อความ",
+ searchMatchModeEdges: "หัวท้าย",
+ searchMatchModeTooltip: "วิธีที่การค้นหาในแถบด้านข้างจับคู่ชื่อ คอมเมนต์ และ Alias: คล้ายกันอนุญาตให้อักขระปรากฏตามลำดับ มีข้อความต้องเป็นข้อความต่อเนื่อง และหัวท้ายต้องอยู่ที่จุดเริ่มต้นหรือจุดสิ้นสุดของชื่อเท่านั้น",
clearFilter: "ล้างตัวกรอง",
locateTargetNotFound: "รายการนี้ไม่พร้อมใช้งานในแถบด้านข้าง อาจถูกลบหรือซ่อนไว้",
locateSqlFile: "ค้นหาในรายการไฟล์ SQL",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index e736ff586f..fbf5a07a17 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -510,6 +510,11 @@ export default withEnglishFallback({
globalLocalSearchTooltip: "Uzak istek olmadan yüklü nesneleri ve önbelleğe alınmış tablo dizinlerini arayın. Eksik dizinleri oluşturmak ve diğer nesneleri uzaktan aramak için kapatın. Meta verileri güncellemek için Yenile düğmesini kullanın.",
regexSearch: "Regex araması",
regexSearchTooltip: "Kenar çubuğu adlarını, açıklamaları ve takma adları JavaScript düzenli ifadeleriyle eşleştirin.",
+ searchMatchMode: "Eşleşme modu",
+ searchMatchModeFuzzy: "Bulanık",
+ searchMatchModeContains: "İçerir",
+ searchMatchModeEdges: "Kenarlar",
+ searchMatchModeTooltip: "Kenar çubuğu aramasının adları, açıklamaları ve takma adları nasıl eşleştirdiği: bulanık karakterlerin sırayla görünmesine izin verir, içerir bitişik bir parça gerektirir, kenarlar metnin adın başında veya sonunda olmasını gerektirir.",
clearFilter: "Filtreyi temizle",
locateTargetNotFound: "Öğe kenar çubuğunda bulunamıyor. Silinmiş veya gizlenmiş olabilir.",
locateSqlFile: "SQL dosya listesinde bul",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 88974972de..9bfa63cdc0 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1338,6 +1338,11 @@ export default withEnglishFallback({
globalLocalSearchTooltip: "搜索已加载的对象和缓存的表索引,不发送远程请求。关闭后构建缺失的索引并远程搜索其他对象。请使用刷新更新元数据。",
regexSearch: "正则搜索",
regexSearchTooltip: "使用 JavaScript 正则表达式匹配侧边栏名称、备注和别名。",
+ searchMatchMode: "匹配方式",
+ searchMatchModeFuzzy: "模糊",
+ searchMatchModeContains: "包含",
+ searchMatchModeEdges: "首尾",
+ searchMatchModeTooltip: "侧边栏搜索如何匹配名称、备注和别名:模糊允许字符按顺序出现,包含要求连续文本,首尾只匹配名称开头或结尾。",
clearFilter: "清除筛选",
locateTargetNotFound: "左侧导航中未找到对应项目,该项目可能已被删除或隐藏。",
locateSqlFile: "在 SQL 文件列表中定位",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index f313e824c7..45a7045155 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -1173,6 +1173,11 @@ export default withEnglishFallback({
globalLocalSearchTooltip: "搜尋已載入的物件與快取的資料表索引,不會發出遠端請求。關閉後可建立缺少的索引並遠端搜尋其他物件。使用重新整理更新中繼資料。",
regexSearch: "正規表示式搜尋",
regexSearchTooltip: "使用 JavaScript 正規表示式比對側邊欄名稱、備註與別名。",
+ searchMatchMode: "比對方式",
+ searchMatchModeFuzzy: "模糊",
+ searchMatchModeContains: "包含",
+ searchMatchModeEdges: "首尾",
+ searchMatchModeTooltip: "側邊欄搜尋如何比對名稱、備註與別名:模糊允許字元依序出現,包含要求連續文字,首尾只比對名稱開頭或結尾。",
clearFilter: "清除篩選",
locateTargetNotFound: "側邊欄中找不到對應項目,該項目可能已被刪除或隱藏。",
locateSqlFile: "在 SQL 檔案清單中定位",
diff --git a/apps/desktop/src/lib/sidebar/sidebarSearch.ts b/apps/desktop/src/lib/sidebar/sidebarSearch.ts
index 8cadb64929..3c2fdb345e 100644
--- a/apps/desktop/src/lib/sidebar/sidebarSearch.ts
+++ b/apps/desktop/src/lib/sidebar/sidebarSearch.ts
@@ -1,6 +1,17 @@
import { compileSearchRegex, parseSlashDelimitedRegexQuery } from "@/lib/common/searchPattern";
-export type SidebarSearchMatchKind = "exact" | "prefix" | "word-prefix" | "substring" | "abbreviation" | "fuzzy" | "regex";
+export type SidebarSearchMatchKind = "exact" | "prefix" | "word-prefix" | "substring" | "suffix" | "abbreviation" | "fuzzy" | "regex";
+
+/**
+ * Foreground match-mode chosen in the sidebar search bar (#13505).
+ *
+ * - `fuzzy`: today's ladder, including in-order subsequences ("101" finds "1001").
+ * - `contains`: a literal LIKE '%q%' filter; abbreviation, subsequence,
+ * cross-word concatenation, and separator-blind tiers are disabled.
+ * - `edges`: only literal whole-label start/end matches; no separator-blind
+ * variants, so mid-name words and separator-spanning queries never match.
+ */
+export type SidebarSearchMatchMode = "fuzzy" | "contains" | "edges";
export interface SidebarSearchMatch {
kind: SidebarSearchMatchKind;
@@ -140,7 +151,7 @@ function testRegex(regex: RegExp, value: string): boolean {
return matched;
}
-function matchSidebarLabelWithRegex(label: string, query: string, regex: RegExp | null, invalidRegex = false): SidebarSearchMatch | null {
+function matchSidebarLabelWithRegex(label: string, query: string, regex: RegExp | null, invalidRegex = false, matchMode: SidebarSearchMatchMode = "fuzzy"): SidebarSearchMatch | null {
if (!query) return null;
if (invalidRegex) return null;
@@ -156,26 +167,40 @@ function matchSidebarLabelWithRegex(label: string, query: string, regex: RegExp
if (lowerLabel === lowerQuery) return { kind: "exact", score: 100 };
if (lowerLabel.startsWith(lowerQuery)) return { kind: "prefix", score: 90 };
+
+ if (matchMode === "edges") {
+ // Strict mode stays literal: only the whole-label start/end counts. The
+ // separator-blind tiers below are fuzzy-only, so "delo" does not match
+ // "del_order" when the user asked for start/end matching. `suffix` only
+ // exists here, so the fuzzy ranking is untouched.
+ if (lowerLabel.endsWith(lowerQuery)) return { kind: "suffix", score: 85 };
+ return null;
+ }
+
if (matchesWordPrefix(label, lowerQuery)) return { kind: "word-prefix", score: 80 };
if (lowerLabel.includes(lowerQuery)) return { kind: "substring", score: 70 };
- if (lowerQuery.length >= 2 && matchesAbbreviation(label, lowerQuery)) return { kind: "abbreviation", score: 60 };
- if (matchesSubsequence(label, lowerQuery)) return { kind: "fuzzy", score: 40 };
-
- // Separator-blind matching: strip underscores, hyphens, dots, spaces,
- // and slashes, then try again. This lets "delo" match "del_order"
- // without typing the underscore separator between prefix and name.
- const stripped = stripSeparators(lowerLabel);
- if (stripped !== lowerLabel && stripped.length >= lowerQuery.length) {
- if (stripped.startsWith(lowerQuery)) return { kind: "word-prefix", score: 65 };
- if (stripped.includes(lowerQuery)) return { kind: "substring", score: 55 };
- }
- // Word-segment prefix concatenation: lets "exclog" find
- // "system_exception_log". Uses the ORIGINAL label so camelCase boundaries
- // survive for word segmentation, and compares case-insensitively. Flat 50
- // keeps it below every existing tier — purely additive.
- if (matchesWordPrefixConcatenation(label, query)) {
- return { kind: "abbreviation", score: 50 };
+ if (matchMode === "fuzzy") {
+ if (lowerQuery.length >= 2 && matchesAbbreviation(label, lowerQuery)) return { kind: "abbreviation", score: 60 };
+ if (matchesSubsequence(label, lowerQuery)) return { kind: "fuzzy", score: 40 };
+
+ // Separator-blind matching: strip underscores, hyphens, dots, spaces,
+ // and slashes, then try again. This lets "delo" match "del_order"
+ // without typing the underscore separator between prefix and name. It is
+ // fuzzy-only because the strict modes promise literal matching.
+ const stripped = stripSeparators(lowerLabel);
+ if (stripped !== lowerLabel && stripped.length >= lowerQuery.length) {
+ if (stripped.startsWith(lowerQuery)) return { kind: "word-prefix", score: 65 };
+ if (stripped.includes(lowerQuery)) return { kind: "substring", score: 55 };
+ }
+
+ // Word-segment prefix concatenation: lets "exclog" find
+ // "system_exception_log". Uses the ORIGINAL label so camelCase boundaries
+ // survive for word segmentation, and compares case-insensitively. Flat 50
+ // keeps it below every existing tier — purely additive.
+ if (matchesWordPrefixConcatenation(label, query)) {
+ return { kind: "abbreviation", score: 50 };
+ }
}
return null;
@@ -183,23 +208,35 @@ function matchSidebarLabelWithRegex(label: string, query: string, regex: RegExp
export interface SidebarSearchMatcherOptions {
regexMode?: boolean;
+ /** Defaults to `"fuzzy"`, i.e. the historical ladder. */
+ matchMode?: SidebarSearchMatchMode;
}
function slashDelimitedCandidate(query: string): boolean {
return query.startsWith("/") && query.lastIndexOf("/") > 0;
}
+/**
+ * Anything outside the union falls back to `fuzzy` (the documented default)
+ * rather than degrading to the more restrictive `contains` ladder.
+ */
+function normalizedMatchMode(mode: SidebarSearchMatchMode | undefined): SidebarSearchMatchMode {
+ return mode === "contains" || mode === "edges" ? mode : "fuzzy";
+}
+
export function createSidebarLabelMatcher(query: string, options: SidebarSearchMatcherOptions = {}): SidebarLabelMatcher {
+ // Regex keeps its own semantics; the mode only gates the plain-text ladder.
+ const matchMode = normalizedMatchMode(options.matchMode);
if (options.regexMode) {
const compiled = compileSearchRegex(query);
- return (label) => matchSidebarLabelWithRegex(label, query, compiled.regex, compiled.invalid);
+ return (label) => matchSidebarLabelWithRegex(label, query, compiled.regex, compiled.invalid, matchMode);
}
const regex = parseSlashDelimitedRegexQuery(query);
// A slash-delimited expression is an explicit regex request even when it is
// malformed. Do not silently reinterpret an invalid pattern as fuzzy text.
const invalidRegex = slashDelimitedCandidate(query) && !regex;
- return (label) => matchSidebarLabelWithRegex(label, query, regex, invalidRegex);
+ return (label) => matchSidebarLabelWithRegex(label, query, regex, invalidRegex, matchMode);
}
export function matchSidebarLabel(label: string, query: string, options: SidebarSearchMatcherOptions = {}): SidebarSearchMatch | null {
diff --git a/packages/app-tests/sidebarSearch.test.ts b/packages/app-tests/sidebarSearch.test.ts
index cd7cf44491..cfaae09067 100644
--- a/packages/app-tests/sidebarSearch.test.ts
+++ b/packages/app-tests/sidebarSearch.test.ts
@@ -1,6 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import { createSidebarLabelMatcher, matchSidebarLabel } from "../../apps/desktop/src/lib/sidebar/sidebarSearch.ts";
+import { createSidebarLabelMatcher, matchSidebarLabel, type SidebarSearchMatchMode } from "../../apps/desktop/src/lib/sidebar/sidebarSearch.ts";
import { compileSearchRegex, parseSlashDelimitedRegexQuery } from "../../apps/desktop/src/lib/common/searchPattern.ts";
import { filterSidebarTree } from "../../apps/desktop/src/lib/sidebar/sidebarSearchTree.ts";
import type { TreeNode } from "../../apps/desktop/src/types/database.ts";
@@ -538,3 +538,142 @@ test("camelCase tokenization survives the real tree-search path (issue #5407)",
assert.equal(findTable(filterSidebarTree(mixedCaseTree, "userorderdetail", new Set()))?.label, "UserOrderDetail");
assert.equal(findTable(filterSidebarTree(mixedCaseTree, "uod", new Set()))?.label, "UserOrderDetail");
});
+
+// ── Foreground match modes (issue #13505) ──
+//
+// `fuzzy` is the default and must stay byte-for-byte identical to the ladder
+// above. `contains` drops the subsequence/abbreviation/concatenation tiers so
+// "101" no longer finds "1001". `edges` keeps only whole-label start/end
+// matches so a mid-name word stops matching.
+
+test("fuzzy remains the default match mode", () => {
+ // No options at all (every pre-#13505 call site) and an explicit "fuzzy"
+ // produce the same results.
+ assert.equal(matchSidebarLabel("1001", "101")?.kind, "fuzzy");
+ assert.equal(matchSidebarLabel("1001", "101")?.score, 40);
+ assert.equal(matchSidebarLabel("1001", "101", { matchMode: "fuzzy" })?.score, 40);
+ assert.equal(matchSidebarLabel("orders", "odr")?.kind, "fuzzy");
+ assert.equal(matchSidebarLabel("orders", "odr", { matchMode: "fuzzy" })?.score, 40);
+ assert.equal(matchSidebarLabel("system_exception_log", "exclog")?.score, 50);
+ assert.equal(matchSidebarLabel("del_order", "elo")?.score, 55);
+ assert.equal(createSidebarLabelMatcher("101")("1001")?.kind, "fuzzy");
+
+ // An out-of-union value (stale persisted state, plugin caller) must degrade to
+ // the documented default, not to the stricter `contains` ladder.
+ const unknownMode = "wildcard" as unknown as SidebarSearchMatchMode;
+ assert.equal(matchSidebarLabel("1001", "101", { matchMode: unknownMode })?.score, 40);
+});
+
+test("contains keeps literal containment and drops subsequence tiers", () => {
+ const contains = (label: string, query: string, score?: number) => {
+ const match = matchSidebarLabel(label, query, { matchMode: "contains" });
+ assert.equal(match?.score, score, `${label} / ${query}`);
+ return match;
+ };
+
+ // Dropped: in-order subsequences and cross-word/quasi tiers.
+ assert.equal(matchSidebarLabel("1001", "101", { matchMode: "contains" }), null);
+ assert.equal(matchSidebarLabel("t_1001", "101", { matchMode: "contains" }), null);
+ assert.equal(matchSidebarLabel("dwd_order_1001", "101", { matchMode: "contains" }), null);
+ assert.equal(matchSidebarLabel("orders", "odr", { matchMode: "contains" }), null);
+ assert.equal(matchSidebarLabel("system_exception_log", "sel", { matchMode: "contains" }), null);
+ // Word-segment prefix concatenation is a fuzzy-only tier too ("exc"+skip+"log").
+ assert.equal(matchSidebarLabel("system_exception_log", "exclog", { matchMode: "contains" }), null);
+
+ // Kept: exact, prefix, word-prefix, substring — all literal contiguous text.
+ assert.equal(contains("101", "101", 100)?.kind, "exact");
+ assert.equal(contains("1010", "101", 90)?.kind, "prefix");
+ assert.equal(contains("t_101", "101", 80)?.kind, "word-prefix");
+ assert.equal(contains("dwd_order_101", "101", 80)?.kind, "word-prefix");
+ assert.equal(contains("x101x", "101", 70)?.kind, "substring");
+ // Strict modes are literal: separator-blind tiers belong to fuzzy only.
+ assert.equal(matchSidebarLabel("del_order", "delo", { matchMode: "contains" }), null);
+ assert.equal(matchSidebarLabel("del_order", "elo", { matchMode: "contains" }), null);
+});
+
+test("edges only matches whole-label start and end", () => {
+ // Exact and prefix are unchanged.
+ assert.equal(matchSidebarLabel("101", "101", { matchMode: "edges" })?.kind, "exact");
+ assert.equal(matchSidebarLabel("101", "101", { matchMode: "edges" })?.score, 100);
+ assert.equal(matchSidebarLabel("1010", "101", { matchMode: "edges" })?.kind, "prefix");
+
+ // Direct suffix is a new tier; it cannot appear in fuzzy mode.
+ assert.equal(matchSidebarLabel("t_101", "101", { matchMode: "edges" })?.kind, "suffix");
+ assert.equal(matchSidebarLabel("t_101", "101", { matchMode: "edges" })?.score, 85);
+ assert.equal(matchSidebarLabel("del_order", "order", { matchMode: "edges" })?.kind, "suffix");
+ assert.equal(matchSidebarLabel("del_order", "order", { matchMode: "edges" })?.score, 85);
+
+ // Mid-name words stop matching, including plain subsequences.
+ assert.equal(matchSidebarLabel("1001", "101", { matchMode: "edges" }), null);
+ assert.equal(matchSidebarLabel("t_1001", "101", { matchMode: "edges" }), null);
+ assert.equal(matchSidebarLabel("dwd_order_1001", "101", { matchMode: "edges" }), null);
+ // `dwd_order_101` genuinely ends with the query, so `edges` keeps it as a
+ // suffix: the mode anchors on the label's start/end, not on the word count.
+ // Its `_detail` sibling is the mid-name case the mode rejects.
+ assert.equal(matchSidebarLabel("dwd_order_101", "101", { matchMode: "edges" })?.kind, "suffix");
+ assert.equal(matchSidebarLabel("dwd_order_101", "101", { matchMode: "edges" })?.score, 85);
+ assert.equal(matchSidebarLabel("dwd_order_101_detail", "101", { matchMode: "edges" }), null);
+
+ // Strict modes are literal: no separator-blind prefix/suffix variants.
+ assert.equal(matchSidebarLabel("del_order", "delo", { matchMode: "edges" }), null);
+ assert.equal(matchSidebarLabel("del_order", "elo", { matchMode: "edges" }), null);
+ assert.equal(matchSidebarLabel("del_order", "delorder", { matchMode: "edges" }), null);
+ assert.equal(matchSidebarLabel("del_order", "elorder", { matchMode: "edges" }), null);
+ assert.equal(matchSidebarLabel("del_order", "order", { matchMode: "edges" })?.kind, "suffix");
+ assert.equal(matchSidebarLabel("del_order", "order", { matchMode: "edges" })?.score, 85);
+});
+
+test("unknown match modes fall back to the fuzzy default", () => {
+ // Runtime values are typed, but the matcher is a public helper; an unexpected
+ // string must not silently degrade to the more restrictive `contains` ladder.
+ assert.equal(matchSidebarLabel("1001", "101", { matchMode: "bogus" as unknown as SidebarSearchMatchMode })?.kind, "fuzzy");
+ assert.equal(matchSidebarLabel("1001", "101", { matchMode: "bogus" as unknown as SidebarSearchMatchMode })?.score, 40);
+});
+
+test("regex mode keeps its semantics regardless of the plain-text mode", () => {
+ for (const matchMode of ["fuzzy", "contains", "edges"] as const) {
+ assert.equal(matchSidebarLabel("SYS_USER_LOG", "/^sys_.*_log$/", { regexMode: true, matchMode })?.kind, "regex");
+ assert.equal(matchSidebarLabel("sys_user_archive", "/^sys_.*_log$/", { regexMode: true, matchMode }), null);
+ assert.equal(matchSidebarLabel("orders", "[", { regexMode: true, matchMode }), null);
+ }
+});
+
+test("filterSidebarTree applies the match mode to labels, comments and aliases", () => {
+ const tree: TreeNode[] = [
+ {
+ id: "conn-1",
+ label: "My Connection",
+ type: "connection",
+ connectionId: "conn-1",
+ isExpanded: true,
+ children: [
+ {
+ id: "db-1",
+ label: "app_db",
+ type: "database",
+ connectionId: "conn-1",
+ database: "app_db",
+ isExpanded: true,
+ children: [
+ { id: "tbl-1001", label: "t_1001", type: "table", connectionId: "conn-1", database: "app_db" },
+ { id: "tbl-101", label: "t_101", type: "table", connectionId: "conn-1", database: "app_db" },
+ { id: "tbl-comment", label: "del_order", type: "table", connectionId: "conn-1", database: "app_db", comment: "101 archive" },
+ { id: "tbl-alias", label: "unrelated", type: "table", connectionId: "conn-1", database: "app_db", searchAliases: ["101"] },
+ ],
+ },
+ ],
+ },
+ ];
+ const labels = (mode: "fuzzy" | "contains" | "edges") => (filterSidebarTree(tree, "101", new Set(), undefined, { matchMode: mode })[0]?.children?.[0]?.children ?? []).map((node) => node.label).sort();
+
+ // The matcher sees every label uniformly: node label, table name, comment
+ // and search aliases. "del_order" only matches through its comment and
+ // "unrelated" only through its alias, so they prove both paths.
+ assert.deepEqual(labels("fuzzy"), ["del_order", "t_1001", "t_101", "unrelated"]);
+ // `contains` drops the in-order subsequence hit on t_1001 but keeps the
+ // comment and alias matches, which are literal containment.
+ assert.deepEqual(labels("contains"), ["del_order", "t_101", "unrelated"]);
+ // `edges` matches "101 archive" (comment prefix) and the exact alias, but
+ // t_101 is a suffix match while t_1001 has no edge.
+ assert.deepEqual(labels("edges"), ["del_order", "t_101", "unrelated"]);
+});