feat(editor): add fold-all shortcuts and toolbar actions

This commit is contained in:
lxk955 authored and GitHub committed 2026-10-03 23:44:45 +08:00
1 parent fc28c4a41e
commit aa2fe831b6
29 files changed
+535 -6

No files matched your search

@@ -2108,6 +2108,8 @@ const formatterEditorShortcutIds: ShortcutActionId[] = [
"uppercaseSelection",
"lowercaseSelection",
"toggleFold",
"foldAll",
"unfoldAll",
];
const formatterEditorShortcutDefinitions = computed(() => formatterEditorShortcutIds.map((id) => SHORTCUT_DEFINITIONS.find((definition) => definition.id === id)).filter((definition): definition is (typeof SHORTCUT_DEFINITIONS)[number] => !!definition));
const filteredShortcutDefinitions = computed(() => {
@@ -102,6 +102,7 @@ import { buildQueryEditorLineNumbersExtension, createQueryEditorLineNumberAlignm
import { keepGuttersAttachedDuringSync } from "@/lib/editor/codemirrorGutterSync";
import { searchKeymapWithoutModD } from "@/lib/editor/codemirrorSearchKeymap";
import { defaultKeymapForGlobalShortcuts } from "@/lib/editor/codemirrorDefaultKeymap";
import { createQueryEditorFoldShortcutBindings, foldKeymapWithoutAllBindings } from "@/lib/editor/queryEditorFoldKeymap";
import { createShowWhitespaceExtension } from "@/lib/editor/codemirrorShowWhitespace";
import { clampEditorFontSize, createEditorWheelZoomGestureGuard, createEditorZoomCommitScheduler, fontSizeFromGestureScale, fontSizeFromWheelDelta } from "@/lib/editor/editorZoom";
@@ -1216,6 +1217,15 @@ const contextMenuActions: QueryEditorContextMenuActions = {
sendSelectionToAi: () => {
if (selectedSql.value.trim()) emit("sendSelectionToAi", selectedSql.value);
},
toggleFoldFromContextMenu: () => {
toggleFold();
},
foldAllFromContextMenu: () => {
foldAll();
},
unfoldAllFromContextMenu: () => {
unfoldAll();
},
};
function getContextMenuState(): QueryEditorContextMenuState {
@@ -1383,6 +1393,7 @@ function runKeymapExtension(codeMirrorKeymap: (typeof import("@codemirror/view")
return codeMirrorRuntime.codeMirrorToggleBlockComment?.(view) ?? false;
}),
...binding(shortcuts.toggleFold, (view) => codeMirrorRuntime.codeMirrorToggleFold?.(view) ?? false),
...createQueryEditorFoldShortcutBindings(shortcuts, foldAllForView, (view) => codeMirrorRuntime.codeMirrorUnfoldAll?.(view) ?? false),
...binding(shortcuts.exPasteSqlInCondition, () => {
if (!supportsSqlInListPaste(props.databaseType)) return false;
void pasteClipboardAsSqlInCondition();
@@ -1978,7 +1989,7 @@ const codeMirrorLifecycle = useQueryEditorCodeMirror({
// Vim must be mounted before DBX/default keymaps so normal-mode keys are handled first.
initializedRuntime.vimModeComp.of(vimModeExtension(initialSettings.vimModeEnabled)),
initializedRuntime.defaultKeymapComp.of(defaultKeymapExtension()),
keymap.of([...searchKeymapWithoutModD(searchKeymap), ...historyKeymap, ...foldKeymap, ...completionKeymap]),
keymap.of([...searchKeymapWithoutModD(searchKeymap), ...historyKeymap, ...foldKeymapWithoutAllBindings(foldKeymap, initializedRuntime.codeMirrorFoldAll, initializedRuntime.codeMirrorUnfoldAll), ...completionKeymap]),
Prec.highest(keymap.of([{ key: "Space", run: acceptSqlServerCompletionOnSpace }])),
initializedRuntime.sqlLanguageComp.of(sqlExtensions.buildSqlLanguageExtension()),
initializedRuntime.sqlSemanticHighlightComp.of(sqlExtensions.buildSqlSemanticHighlightExtension()),
@@ -2738,6 +2749,33 @@ function cancelGutterExecutionViewport(requestId: number) {
return executionViewportOwnership.cancelPendingRequest(requestId);
}
function toggleFold(): boolean {
if (!view.value) return false;
return codeMirrorRuntime.codeMirrorToggleFold?.(view.value) ?? false;
}
function foldAllForView(currentView: EditorViewType): boolean {
const command = codeMirrorRuntime.codeMirrorFoldAll;
if (!command) return false;
if (!shouldUseQueryEditorLargeDocumentModeForSize(currentView.state.doc.length, currentView.state.doc.lines)) return command(currentView);
const expectedDoc = currentView.state.doc;
void statementBoundaries.ensureStatementCache(currentView.state).then((result) => {
if (!result || view.value !== currentView || currentView.state.doc !== expectedDoc) return;
command(currentView);
});
return true;
}
function foldAll(): boolean {
if (!view.value) return false;
return foldAllForView(view.value);
}
function unfoldAll(): boolean {
if (!view.value) return false;
return codeMirrorRuntime.codeMirrorUnfoldAll?.(view.value) ?? false;
}
function shouldBlockExecutionShortcut(event?: KeyboardEvent, currentView: EditorViewType | null = view.value): boolean {
return (currentView ? isEditorComposing(currentView) : false) || (event ? postCompositionKeyGuard.blocks(event) : false);
}
@@ -2759,6 +2797,9 @@ defineExpose({
focusErrorPosition,
previewStatementRange,
refreshCompletionCache,
toggleFold,
foldAll,
unfoldAll,
});
</script>
@@ -1,7 +1,37 @@
<script setup lang="ts">
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { AlignLeft, Camera, CaseLower, CaseSensitive, CaseUpper, ClipboardPaste, Code2, Columns3, Download, Eye, FileCode, Highlighter, MessageSquareText, Minimize2, Pencil, PencilRuler, Play, Copy, List, Scissors, Search, Sparkles, Table2, TextSelect, Trash2, WandSparkles } from "@lucide/vue";
import {
AlignLeft,
Camera,
CaseLower,
CaseSensitive,
CaseUpper,
ChevronsUpDown,
ClipboardPaste,
Code2,
Columns3,
Download,
Eye,
FileCode,
FoldVertical,
Highlighter,
MessageSquareText,
Minimize2,
Pencil,
PencilRuler,
Play,
Copy,
List,
Scissors,
Search,
Sparkles,
Table2,
TextSelect,
Trash2,
UnfoldVertical,
WandSparkles,
} from "@lucide/vue";
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import { canFormatSqlForDatabaseType } from "@/lib/sql/sqlFormatter";
import { supportsQueryEditorBlockComments } from "@/lib/database/databaseFeatureSupport";
@@ -47,6 +77,9 @@ export interface QueryEditorContextMenuActions {
emitContextObjectAction: (action: QueryContextObjectAction) => void;
openCodeSnapshot: () => void;
sendSelectionToAi: () => void;
toggleFoldFromContextMenu?: () => void;
foldAllFromContextMenu?: () => void;
unfoldAllFromContextMenu?: () => void;
}
const props = defineProps<{ getState: () => QueryEditorContextMenuState; actions: QueryEditorContextMenuActions }>();
@@ -183,6 +216,30 @@ const contextMenuItems = computed<ContextMenuItem[]>(() => {
disabled: state.readOnly || !canCopySelectedSql,
icon: Minimize2,
},
{
label: t("editor.contextMenu.folding"),
icon: ChevronsUpDown,
children: [
{
label: t("editor.contextMenu.toggleFold"),
action: () => actions.toggleFoldFromContextMenu?.(),
icon: ChevronsUpDown,
shortcut: shortcuts.toggleFold,
},
{
label: t("editor.contextMenu.foldAll"),
action: () => actions.foldAllFromContextMenu?.(),
icon: FoldVertical,
shortcut: shortcuts.foldAll,
},
{
label: t("editor.contextMenu.unfoldAll"),
action: () => actions.unfoldAllFromContextMenu?.(),
icon: UnfoldVertical,
shortcut: shortcuts.unfoldAll,
},
],
},
{
label: t("editor.contextMenu.copySelection"),
action: actions.copySelectedSqlFromContextMenu,
@@ -6,6 +6,7 @@ import { createI18n } from "vue-i18n";
import { EditorSelection } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { toggleLineComment, undo } from "@codemirror/commands";
import { foldedRanges } from "@codemirror/language";
import { closeCompletion, completionStatus, currentCompletions, selectedCompletionIndex, startCompletion } from "@codemirror/autocomplete";
import { afterEach, describe, expect, it, vi } from "vitest";
import QueryEditor from "../QueryEditor.vue";
@@ -78,6 +79,12 @@ function keydown(target: HTMLElement, key: string) {
return event;
}
function foldedRangeCount(view: EditorView): number {
let count = 0;
foldedRanges(view.state).between(0, view.state.doc.length, () => count++);
return count;
}
describe("QueryEditor component split integration", () => {
it("executes each IRIS query separately after the Contains operator", async () => {
const first = "select * from oec_order_adminstatus where STAT_Code [ '123'";
@@ -305,6 +312,17 @@ describe("QueryEditor component split integration", () => {
expect(view.state.doc.toString()).toBe("SELECT 1;\nSELECT 2;");
});
it("folds and unfolds all available ranges through the exposed handles", async () => {
const source = "BEGIN\nSELECT 1;\nEND;\n\nBEGIN\nSELECT 2;\nEND;";
const { editor, view } = await mountEditor({ modelValue: source });
expect(typeof editor.foldAll).toBe("function");
expect(typeof editor.unfoldAll).toBe("function");
expect(editor.foldAll()).toBe(true);
expect(foldedRangeCount(view)).toBe(2);
expect(editor.unfoldAll()).toBe(true);
expect(foldedRangeCount(view)).toBe(0);
});
it("isolates extension reconfiguration and disposal between editor instances", async () => {
const first = await mountEditor({ modelValue: "SELECT 1;", tabId: "independent-a" });
const second = await mountEditor({ modelValue: "SELECT 2;", tabId: "independent-b" });
@@ -3,7 +3,7 @@
import { createApp, h, nextTick, ref, shallowRef, type App } from "vue";
import { createPinia, setActivePinia } from "pinia";
import { createI18n } from "vue-i18n";
import { language } from "@codemirror/language";
import { foldedRanges, language } from "@codemirror/language";
import { EditorView } from "@codemirror/view";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { QUERY_EDITOR_FULL_FEATURE_MAX_DOCUMENT_LENGTH, QUERY_EDITOR_FULL_FEATURE_MAX_LINE_COUNT } from "@/lib/editor/queryEditorLargeDocument";
@@ -13,6 +13,7 @@ const analysisProbe = vi.hoisted(() => ({
documentLengths: [] as number[],
documentLineCounts: [] as number[],
backgroundDocuments: [] as string[],
backgroundGate: null as Promise<void> | null,
failAtLength: Number.POSITIVE_INFINITY,
failAtLineCount: Number.POSITIVE_INFINITY,
}));
@@ -33,7 +34,11 @@ vi.mock("@/lib/sql/executableStatementRangeCache", async (importOriginal) => {
vi.mock("@/lib/sql/sqlStatementAnalysisWorker", async () => {
const actual = await vi.importActual<typeof import("@/lib/sql/executableStatementRangeCache")>("@/lib/sql/executableStatementRangeCache");
const { Text } = await import("@codemirror/state");
const { EditorState, Text } = await import("@codemirror/state");
const langSql = await import("@codemirror/lang-sql");
const { ensureSyntaxTree } = await import("@codemirror/language");
const { createDbxCodeMirrorSqlDialect } = await import("@/lib/editor/codemirrorSqlDialect");
const { computeBlockFoldRanges } = await import("@/lib/editor/codemirrorSqlBlockFolding");
return {
createSqlStatementAnalysisWorker: () => {
let generation = 0;
@@ -41,10 +46,15 @@ vi.mock("@/lib/sql/sqlStatementAnalysisWorker", async () => {
async analyze(request: import("@/lib/sql/sqlStatementAnalysis").SqlStatementAnalysisRequest) {
const current = ++generation;
analysisProbe.backgroundDocuments.push(request.sql);
if (analysisProbe.backgroundGate) await analysisProbe.backgroundGate;
await Promise.resolve();
if (current !== generation) return null;
const { doc: _doc, ...result } = actual.executableStatementRangeCacheForDoc(null, Text.of(request.sql.split("\n")), request.databaseType, request.parameterOptions);
return result;
if (!request.includeFolds) return result;
const state = EditorState.create({ doc: request.sql, extensions: [langSql.sql({ dialect: createDbxCodeMirrorSqlDialect(langSql, request.syntaxDialect ?? "mysql", request.databaseType, request.driverProfile) })] });
let tree = ensureSyntaxTree(state, state.doc.length, 1000);
while (!tree) tree = ensureSyntaxTree(state, state.doc.length, 1000);
return { ...result, folds: computeBlockFoldRanges(state, request.databaseType, tree) };
},
cancel() {
generation++;
@@ -83,6 +93,7 @@ beforeEach(() => {
analysisProbe.documentLengths = [];
analysisProbe.documentLineCounts = [];
analysisProbe.backgroundDocuments = [];
analysisProbe.backgroundGate = null;
analysisProbe.failAtLength = Number.POSITIVE_INFINITY;
analysisProbe.failAtLineCount = Number.POSITIVE_INFINITY;
});
@@ -126,6 +137,12 @@ async function mountEditor(modelValue: string, overrides: Partial<QueryEditorPro
return { editor: editor.value!, host, onUpdateModelValue, view };
}
function foldedRangeCount(view: EditorView): number {
let count = 0;
foldedRanges(view.state).between(0, view.state.doc.length, () => count++);
return count;
}
describe("QueryEditor large document mode", () => {
it("keeps the full editor feature path for ordinary documents", async () => {
const source = oraclePackage(8);
@@ -151,6 +168,22 @@ describe("QueryEditor large document mode", () => {
expect(analysisProbe.backgroundDocuments).toContain(source);
});
it("waits for background fold analysis before folding a large document", async () => {
const source = `BEGIN\n${"SELECT 1;\n".repeat(QUERY_EDITOR_FULL_FEATURE_MAX_LINE_COUNT)}END;`;
let releaseBackgroundAnalysis!: () => void;
analysisProbe.backgroundGate = new Promise<void>((resolve) => {
releaseBackgroundAnalysis = resolve;
});
const { editor, view } = await mountEditor(source);
expect(editor.foldAll()).toBe(true);
expect(foldedRangeCount(view)).toBe(0);
releaseBackgroundAnalysis();
await vi.waitFor(() => expect(foldedRangeCount(view)).toBe(1), { timeout: 5000 });
expect(editor.unfoldAll()).toBe(true);
expect(foldedRangeCount(view)).toBe(0);
});
it("enters bounded mode when typing crosses the line budget", async () => {
const source = Array.from({ length: QUERY_EDITOR_FULL_FEATURE_MAX_LINE_COUNT }, (_, index) => `SELECT ${index};`).join("\n");
const { host, view } = await mountEditor(source);
@@ -38,6 +38,9 @@ function mountMenu() {
emitContextObjectAction: vi.fn(),
openCodeSnapshot: vi.fn(),
sendSelectionToAi: vi.fn(),
toggleFoldFromContextMenu: vi.fn(),
foldAllFromContextMenu: vi.fn(),
unfoldAllFromContextMenu: vi.fn(),
} satisfies QueryEditorContextMenuActions;
const onClose = vi.fn();
let synchronize = () => {};
@@ -199,4 +202,25 @@ describe("QueryEditor extracted context menu", () => {
});
expect(button("contextMenu.viewData").disabled).toBe(true);
});
it("routes folding actions from the folding submenu", async () => {
const { actions, open } = mountMenu();
await open();
button("editor.contextMenu.folding").dispatchEvent(new MouseEvent("mouseenter", { bubbles: true }));
await nextTick();
button("editor.contextMenu.toggleFold").click();
expect(actions.toggleFoldFromContextMenu).toHaveBeenCalledTimes(1);
await open();
button("editor.contextMenu.folding").dispatchEvent(new MouseEvent("mouseenter", { bubbles: true }));
await nextTick();
button("editor.contextMenu.foldAll").click();
expect(actions.foldAllFromContextMenu).toHaveBeenCalledTimes(1);
await open();
button("editor.contextMenu.folding").dispatchEvent(new MouseEvent("mouseenter", { bubbles: true }));
await nextTick();
button("editor.contextMenu.unfoldAll").click();
expect(actions.unfoldAllFromContextMenu).toHaveBeenCalledTimes(1);
});
});
@@ -66,6 +66,8 @@ interface CodeMirrorBindings {
codeMirrorToggleBlockComment: typeof import("@codemirror/commands").toggleBlockComment | null;
codeMirrorDefaultKeymap: readonly import("@codemirror/view").KeyBinding[] | null;
codeMirrorToggleFold: typeof import("@codemirror/language").toggleFold | null;
codeMirrorFoldAll: typeof import("@codemirror/language").foldAll | null;
codeMirrorUnfoldAll: typeof import("@codemirror/language").unfoldAll | null;
setSqlDiagnosticsEffect: import("@codemirror/state").StateEffectType<SqlSemanticDiagnostic[]> | null;
setPreviewRangeEffect:
| import("@codemirror/state").StateEffectType<{
@@ -148,6 +150,8 @@ type ReadyCodeMirrorBindings = CodeMirrorBindings & {
| "codeMirrorToggleBlockComment"
| "codeMirrorDefaultKeymap"
| "codeMirrorToggleFold"
| "codeMirrorFoldAll"
| "codeMirrorUnfoldAll"
| "codeMirrorIndentUnit"]: NonNullable<CodeMirrorBindings[Key]>;
};
@@ -216,6 +220,8 @@ export function createQueryEditorCodeMirrorRuntime() {
codeMirrorToggleBlockComment: null,
codeMirrorDefaultKeymap: null,
codeMirrorToggleFold: null,
codeMirrorFoldAll: null,
codeMirrorUnfoldAll: null,
setSqlDiagnosticsEffect: null,
setPreviewRangeEffect: null,
setResultSourceRangeEffect: null,
@@ -277,7 +283,7 @@ export function createQueryEditorCodeMirrorRuntime() {
setSelectedCompletion,
},
{ copyLineDown, copyLineUp, deleteLine, indentLess, indentMore, insertNewlineKeepIndent, moveLineDown, moveLineUp, redo, selectAll, undo, toggleLineComment, toggleBlockComment, history, defaultKeymap, historyKeymap },
{ bracketMatching, foldGutter, indentOnInput, indentUnit, syntaxHighlighting, defaultHighlightStyle, foldKeymap, toggleFold, ensureSyntaxTree, highlightingFor, syntaxTree },
{ bracketMatching, foldGutter, indentOnInput, indentUnit, syntaxHighlighting, defaultHighlightStyle, foldKeymap, toggleFold, foldAll, unfoldAll, ensureSyntaxTree, highlightingFor, syntaxTree },
{ searchKeymap },
] = await Promise.all([import("@codemirror/view"), import("@codemirror/state"), import("@codemirror/lang-sql"), import("@codemirror/autocomplete"), import("@codemirror/commands"), import("@codemirror/language"), import("@codemirror/search")]);
runtime.editorViewModule = {
@@ -345,6 +351,8 @@ export function createQueryEditorCodeMirrorRuntime() {
runtime.codeMirrorToggleBlockComment = toggleBlockComment;
runtime.codeMirrorDefaultKeymap = defaultKeymap;
runtime.codeMirrorToggleFold = toggleFold;
runtime.codeMirrorFoldAll = foldAll;
runtime.codeMirrorUnfoldAll = unfoldAll;
runtime.codeMirrorIndentUnit = indentUnit;
return {
runtime: runtime as ReadyCodeMirrorBindings,
@@ -1650,6 +1650,14 @@ function cancelQueryEditorExecutionViewport(requestId: number) {
return queryEditorRef.value?.cancelGutterExecutionViewport(requestId) ?? false;
}
function foldAll(): boolean {
return queryEditorRef.value?.foldAll?.() ?? false;
}
function unfoldAll(): boolean {
return queryEditorRef.value?.unfoldAll?.() ?? false;
}
async function handleExportQuery(payload: { sql: string; format: "csv" | "xlsx" | "txt"; columnComments?: (string | null)[] }) {
const tab = props.activeTab;
if (!tab || tab.mode !== "query") return;
@@ -1795,6 +1803,8 @@ defineExpose({
focusStatementRange,
focusErrorPosition,
locateActiveResultError,
foldAll,
unfoldAll,
});
</script>
@@ -215,6 +215,8 @@ const groupExecutableSql = computed(() => {
@explain="activeTab && toolbar.explain(activeTab.id)"
@format-sql="activeTab && toolbar.formatSql(activeTab.id)"
@compress-sql="activeTab && toolbar.compressSql(activeTab.id)"
@fold-all="activeSurfaceRef?.foldAll?.()"
@unfold-all="activeSurfaceRef?.unfoldAll?.()"
@toggle-sql-keyword-case="toolbar.toggleSqlKeywordCase()"
@save-sql="(tabId: string) => toolbar.saveSql(tabId)"
@open-sql="toolbar.openSqlFile()"
@@ -21,6 +21,8 @@ import {
AlertTriangle,
ClipboardPaste,
Minimize2,
FoldVertical,
UnfoldVertical,
SpellCheck2,
Layers,
MoreHorizontal,
@@ -99,6 +101,8 @@ const emit = defineEmits<{
"update:explainMode": [mode: "explain" | "autotrace"];
formatSql: [];
compressSql: [];
foldAll: [];
unfoldAll: [];
toggleSqlKeywordCase: [];
saveSql: [tabId: string];
openSql: [];
@@ -459,6 +463,15 @@ const canFormatSql = computed(() => canFormatSqlForDatabaseType(props.activeConn
const showFormatButton = computed(() => canFormatSql.value && toolbarTier.value < 2);
const showExplainAnalyzeToggle = computed(() => toolbarTier.value < 3);
const showCompressButton = computed(() => toolbarTier.value < 1);
const showFoldButtons = computed(() => toolbarTier.value < 1);
const foldAllTooltip = computed(() => {
const shortcut = formatShortcutDisplay(settingsStore.editorSettings.shortcuts.foldAll);
return shortcut ? `${t("toolbar.foldAll")} (${shortcut})` : t("toolbar.foldAll");
});
const unfoldAllTooltip = computed(() => {
const shortcut = formatShortcutDisplay(settingsStore.editorSettings.shortcuts.unfoldAll);
return shortcut ? `${t("toolbar.unfoldAll")} (${shortcut})` : t("toolbar.unfoldAll");
});
const showKeywordCaseButton = computed(() => toolbarTier.value < 1);
const showWordWrapButton = computed(() => toolbarTier.value < 1);
const showSemanticDiagnosticsButton = computed(() => supportsSqlSemanticDiagnosticsToggle.value && toolbarTier.value < 1);
@@ -616,6 +629,22 @@ async function changeCatalog(selectedCatalog: string) {
</TooltipTrigger>
<TooltipContent>{{ t("toolbar.compressSql") }}</TooltipContent>
</Tooltip>
<Tooltip v-if="showFoldButtons">
<TooltipTrigger as-child>
<Button variant="ghost" size="icon" class="h-6 w-6 text-muted-foreground hover:bg-muted hover:text-foreground" :disabled="activeTab.isExecuting || activeTab.isExplaining || !activeTab.sql.trim()" :aria-label="t('toolbar.foldAll')" @click="emit('foldAll')">
<FoldVertical class="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>{{ foldAllTooltip }}</TooltipContent>
</Tooltip>
<Tooltip v-if="showFoldButtons">
<TooltipTrigger as-child>
<Button variant="ghost" size="icon" class="h-6 w-6 text-muted-foreground hover:bg-muted hover:text-foreground" :disabled="activeTab.isExecuting || activeTab.isExplaining || !activeTab.sql.trim()" :aria-label="t('toolbar.unfoldAll')" @click="emit('unfoldAll')">
<UnfoldVertical class="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>{{ unfoldAllTooltip }}</TooltipContent>
</Tooltip>
<Tooltip v-if="showKeywordCaseButton">
<TooltipTrigger as-child>
<Button
@@ -762,6 +791,14 @@ async function changeCatalog(selectedCatalog: string) {
<Minimize2 class="h-3.5 w-3.5" />
{{ t("toolbar.compressSql") }}
</DropdownMenuItem>
<DropdownMenuItem :disabled="activeTab.isExecuting || activeTab.isExplaining || !activeTab.sql.trim()" @select="emit('foldAll')">
<FoldVertical class="h-3.5 w-3.5" />
{{ t("toolbar.foldAll") }}
</DropdownMenuItem>
<DropdownMenuItem :disabled="activeTab.isExecuting || activeTab.isExplaining || !activeTab.sql.trim()" @select="emit('unfoldAll')">
<UnfoldVertical class="h-3.5 w-3.5" />
{{ t("toolbar.unfoldAll") }}
</DropdownMenuItem>
<DropdownMenuItem @select="emit('toggleSqlKeywordCase')">
<span class="inline-flex h-4 w-4 shrink-0 items-center justify-center font-mono text-xs font-semibold" aria-hidden="true">
{{ keywordCaseIsLower ? "A" : "a" }}
@@ -45,6 +45,8 @@ defineExpose<QueryEditorSurfaceHandle>({
previewStatementRange: (range: StatementRange | null) => contentAreaRef.value?.previewStatementRange(range) ?? false,
focusStatementRange: (range: StatementRange | null) => contentAreaRef.value?.focusStatementRange(range) ?? false,
focusErrorPosition: (offset: number) => contentAreaRef.value?.focusErrorPosition(offset) ?? false,
foldAll: () => contentAreaRef.value?.foldAll() ?? false,
unfoldAll: () => contentAreaRef.value?.unfoldAll() ?? false,
});
</script>
@@ -574,4 +574,65 @@ describe("EditorToolbar mount contract", () => {
app.unmount();
host.remove();
});
it("emits foldAll and unfoldAll when clicking the fold/unfold toolbar buttons", async () => {
const connectionStore = useConnectionStore();
connectionStore.connections = [
{
id: "conn-1",
name: "conn",
db_type: "mysql",
color: "",
} as never,
];
const host = createHost();
const onFoldAll = vi.fn();
const onUnfoldAll = vi.fn();
const app = createApp(EditorToolbar, {
activeTab: {
id: "tab-1",
title: "SQL",
connectionId: "conn-1",
database: "db",
sql: "SELECT 1;\nSELECT 2;",
mode: "query",
isExecuting: false,
isCancelling: false,
isExplaining: false,
},
activeConnection: connectionStore.getConfig("conn-1"),
executableSql: "SELECT 1;\nSELECT 2;",
explainMode: "explain",
blockDangerousRedisCommands: false,
sqlKeywordCase: "preserve",
databaseRequiredSignal: 0,
autoCommit: true,
txnSessionId: undefined,
txnAutoRolledBack: false,
txnPossiblyDirty: false,
stickyProvenReadOnlyState: false,
onFoldAll,
onUnfoldAll,
});
app.use(pinia);
app.use(i18n);
app.mount(host);
await nextTick();
const foldAllButton = host.querySelector<HTMLButtonElement>('button[aria-label="toolbar.foldAll"]');
expect(foldAllButton).not.toBeNull();
foldAllButton?.dispatchEvent(new MouseEvent("click", { detail: 1, bubbles: true }));
await nextTick();
expect(onFoldAll).toHaveBeenCalledTimes(1);
const unfoldAllButton = host.querySelector<HTMLButtonElement>('button[aria-label="toolbar.unfoldAll"]');
expect(unfoldAllButton).not.toBeNull();
unfoldAllButton?.dispatchEvent(new MouseEvent("click", { detail: 1, bubbles: true }));
await nextTick();
expect(onUnfoldAll).toHaveBeenCalledTimes(1);
app.unmount();
host.remove();
});
});
@@ -42,6 +42,8 @@ export interface QueryEditorSurfaceHandle {
previewStatementRange(range: StatementRange | null): boolean;
focusStatementRange(range: StatementRange | null): boolean;
focusErrorPosition(offset: number): boolean;
foldAll?(): boolean;
unfoldAll?(): boolean;
}
export interface QueryResultSurfaceHandle {