feat(editor): add fold-all shortcuts and toolbar actions
This commit is contained in:
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,
|
||||
|
||||
Vendored
+18
@@ -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" });
|
||||
|
||||
+36
-3
@@ -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);
|
||||
|
||||
+24
@@ -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 {
|
||||
|
||||
@@ -219,6 +219,8 @@ export default withEnglishFallback({
|
||||
formatSqlFailed: "SQL-i formatlamaq mümkün olmadı",
|
||||
formatAutoDetectFailed: "Seçilmiş məzmunu tanımaq və ya formatlamaq mümkün deyil",
|
||||
compressSql: "SQL-i sıxlaşdır",
|
||||
foldAll: "Hamısını bük",
|
||||
unfoldAll: "Hamısını aç",
|
||||
keywordCaseLower: "SQL açar sözlərini kiçik hərflərlə yaz",
|
||||
keywordCaseUpper: "SQL açar sözlərini böyük hərflərlə yaz",
|
||||
sqlSemanticDiagnosticsToggleOn: "SQL semantik diaqnostikası: aktiv (deaktiv etmək üçün klikləyin)",
|
||||
@@ -1486,6 +1488,10 @@ export default withEnglishFallback({
|
||||
blockCommentSelection: "Seçimi blok şərhinə çevir",
|
||||
formatSelectionSql: "Seçilmiş SQL-i formatla",
|
||||
compressSelectionSql: "Seçilmiş SQL-i sıxlaşdır",
|
||||
folding: "Qatlama",
|
||||
toggleFold: "Qatlamanı aç/bağla",
|
||||
foldAll: "Hamısını bük",
|
||||
unfoldAll: "Hamısını aç",
|
||||
cutSelection: "Seçimi kəs",
|
||||
pasteFromClipboard: "Yerləşdir",
|
||||
pasteRestoringSourceSql: "Yapışdır və mənbə SQL-i bərpa et",
|
||||
@@ -7711,6 +7717,8 @@ export default withEnglishFallback({
|
||||
intentionUnqualifyIdentifier: "İdentifikatoru qısa adla göstər",
|
||||
intentionBatchQualifyIdentifiers: "İdentifikatorları toplu şəkildə tam adla göstər",
|
||||
shortcutToggleFold: "Qatlamanı aç/bağla",
|
||||
shortcutFoldAll: "Hamısını bük",
|
||||
shortcutUnfoldAll: "Hamısını aç",
|
||||
shortcutScopeGlobal: "Qlobal",
|
||||
shortcutScopeEditor: "SQL redaktoru",
|
||||
shortcutScopeGrid: "Məlumat cədvəli",
|
||||
|
||||
@@ -395,6 +395,8 @@ export default {
|
||||
formatSqlFailed: "Failed to format SQL",
|
||||
formatAutoDetectFailed: "Cannot recognize or format the selected content",
|
||||
compressSql: "Compress SQL",
|
||||
foldAll: "Fold all",
|
||||
unfoldAll: "Unfold all",
|
||||
keywordCaseLower: "Use lower-case SQL keywords",
|
||||
keywordCaseUpper: "Use upper-case SQL keywords",
|
||||
sqlSemanticDiagnosticsToggleOn: "SQL semantic diagnostics: On (click to disable)",
|
||||
@@ -1783,6 +1785,10 @@ export default {
|
||||
blockCommentSelection: "Block comment selection",
|
||||
formatSelectionSql: "Format selected SQL",
|
||||
compressSelectionSql: "Compress selected SQL",
|
||||
folding: "Folding",
|
||||
toggleFold: "Toggle fold",
|
||||
foldAll: "Fold all",
|
||||
unfoldAll: "Unfold all",
|
||||
cutSelection: "Cut selection",
|
||||
pasteFromClipboard: "Paste",
|
||||
pasteRestoringSourceSql: "Paste and restore source SQL",
|
||||
@@ -8624,6 +8630,8 @@ export default {
|
||||
intentionUnqualifyIdentifier: "Unqualify Identifier",
|
||||
intentionBatchQualifyIdentifiers: "Batch Qualify Identifiers",
|
||||
shortcutToggleFold: "Toggle fold",
|
||||
shortcutFoldAll: "Fold all",
|
||||
shortcutUnfoldAll: "Unfold all",
|
||||
shortcutScopeGlobal: "Global",
|
||||
shortcutScopeEditor: "SQL editor",
|
||||
shortcutScopeGrid: "Data grid",
|
||||
|
||||
@@ -388,6 +388,8 @@ export default withEnglishFallback({
|
||||
formatSqlFailed: "Error al formatear el SQL",
|
||||
formatAutoDetectFailed: "No se pudo reconocer ni formatear el contenido seleccionado",
|
||||
compressSql: "Comprimir SQL",
|
||||
foldAll: "Contraer todo",
|
||||
unfoldAll: "Expandir todo",
|
||||
keywordCaseLower: "Usar palabras clave SQL en minúsculas",
|
||||
keywordCaseUpper: "Usar palabras clave SQL en mayúsculas",
|
||||
sqlSemanticDiagnosticsToggleOn: "Diagnóstico semántico de SQL: activado (clic para desactivar)",
|
||||
@@ -1772,6 +1774,10 @@ export default withEnglishFallback({
|
||||
blockCommentSelection: "Comentario de bloque en la selección",
|
||||
formatSelectionSql: "Formatear SQL seleccionado",
|
||||
compressSelectionSql: "Comprimir SQL seleccionado",
|
||||
folding: "Plegado de código",
|
||||
toggleFold: "Contraer/expandir código",
|
||||
foldAll: "Contraer todo",
|
||||
unfoldAll: "Expandir todo",
|
||||
sendToAi: "Enviar a IA",
|
||||
uppercaseSelection: "Convertir a mayusculas",
|
||||
lowercaseSelection: "Convertir a minusculas",
|
||||
@@ -7924,6 +7930,8 @@ export default withEnglishFallback({
|
||||
intentionUnqualifyIdentifier: "Descalificar identificador",
|
||||
intentionBatchQualifyIdentifiers: "Calificar identificadores en lote",
|
||||
shortcutToggleFold: "Contraer/expandir código",
|
||||
shortcutFoldAll: "Contraer todo",
|
||||
shortcutUnfoldAll: "Expandir todo",
|
||||
shortcutScopeGlobal: "Global",
|
||||
shortcutScopeEditor: "Editor SQL",
|
||||
shortcutScopeGrid: "Cuadrícula de datos",
|
||||
|
||||
@@ -334,6 +334,8 @@ export default withEnglishFallback({
|
||||
formatSqlFailed: "Gagal memformat SQL",
|
||||
formatAutoDetectFailed: "Tidak dapat mengenali atau memformat konten yang dipilih",
|
||||
compressSql: "Kompres SQL",
|
||||
foldAll: "Lipat semua",
|
||||
unfoldAll: "Buka semua lipatan",
|
||||
keywordCaseLower: "Gunakan kata kunci SQL huruf kecil",
|
||||
keywordCaseUpper: "Gunakan kata kunci SQL huruf besar",
|
||||
sqlSemanticDiagnosticsToggleOn: "Diagnostik semantik SQL: Aktif (klik untuk menonaktifkan)",
|
||||
@@ -1721,6 +1723,10 @@ export default withEnglishFallback({
|
||||
blockCommentSelection: "Jadikan komentar blok pilihan",
|
||||
formatSelectionSql: "Format SQL terpilih",
|
||||
compressSelectionSql: "Kompres SQL terpilih",
|
||||
folding: "Lipat",
|
||||
toggleFold: "Aktifkan/nonaktifkan lipat",
|
||||
foldAll: "Lipat semua",
|
||||
unfoldAll: "Buka semua lipatan",
|
||||
cutSelection: "Potong pilihan",
|
||||
pasteFromClipboard: "Tempel",
|
||||
pasteRestoringSourceSql: "Tempel dan pulihkan SQL sumber",
|
||||
@@ -8436,6 +8442,8 @@ export default withEnglishFallback({
|
||||
intentionUnqualifyIdentifier: "Batalkan Kualifikasi Identifier",
|
||||
intentionBatchQualifyIdentifiers: "Kualifikasikan Identifier Secara Batch",
|
||||
shortcutToggleFold: "Aktifkan/nonaktifkan lipat",
|
||||
shortcutFoldAll: "Lipat semua",
|
||||
shortcutUnfoldAll: "Buka semua lipatan",
|
||||
shortcutScopeGlobal: "Global",
|
||||
shortcutScopeEditor: "Editor SQL",
|
||||
shortcutScopeGrid: "Grid data",
|
||||
|
||||
@@ -382,6 +382,8 @@ export default withEnglishFallback({
|
||||
formatSqlFailed: "Impossibile formattare SQL",
|
||||
formatAutoDetectFailed: "Impossibile riconoscere o formattare il contenuto selezionato",
|
||||
compressSql: "Comprimi SQL",
|
||||
foldAll: "Comprimi tutto",
|
||||
unfoldAll: "Espandi tutto",
|
||||
keywordCaseLower: "Usa parole chiave SQL minuscole",
|
||||
keywordCaseUpper: "Usa parole chiave SQL maiuscole",
|
||||
sqlSemanticDiagnosticsToggleOn: "Diagnostica semantica SQL: attiva (clic per disattivare)",
|
||||
@@ -1681,6 +1683,10 @@ export default withEnglishFallback({
|
||||
blockCommentSelection: "Commenta selezione a blocco",
|
||||
formatSelectionSql: "Formatta SQL selezionato",
|
||||
compressSelectionSql: "Comprimi SQL selezionato",
|
||||
folding: "Compressione codice",
|
||||
toggleFold: "Comprimi/espandi codice",
|
||||
foldAll: "Comprimi tutto",
|
||||
unfoldAll: "Espandi tutto",
|
||||
sendToAi: "Invia ad AI",
|
||||
uppercaseSelection: "Converti in maiuscolo",
|
||||
lowercaseSelection: "Converti in minuscolo",
|
||||
@@ -7686,6 +7692,8 @@ export default withEnglishFallback({
|
||||
intentionUnqualifyIdentifier: "Rimuovi qualifica",
|
||||
intentionBatchQualifyIdentifiers: "Qualifica identificatori in batch",
|
||||
shortcutToggleFold: "Comprimi/espandi codice",
|
||||
shortcutFoldAll: "Comprimi tutto",
|
||||
shortcutUnfoldAll: "Espandi tutto",
|
||||
shortcutScopeGlobal: "Globale",
|
||||
shortcutScopeEditor: "Editor SQL",
|
||||
shortcutScopeGrid: "Griglia dati",
|
||||
|
||||
@@ -383,6 +383,8 @@ export default withEnglishFallback({
|
||||
formatSqlFailed: "SQLのフォーマットに失敗しました",
|
||||
formatAutoDetectFailed: "選択内容を認識またはフォーマットできません",
|
||||
compressSql: "SQLを圧縮",
|
||||
foldAll: "すべて折りたたむ",
|
||||
unfoldAll: "すべて展開",
|
||||
keywordCaseLower: "SQLキーワードを小文字にする",
|
||||
keywordCaseUpper: "SQLキーワードを大文字にする",
|
||||
sqlSemanticDiagnosticsToggleOn: "SQLセマンティック診断:オン(クリックでオフ)",
|
||||
@@ -1701,6 +1703,10 @@ export default withEnglishFallback({
|
||||
blockCommentSelection: "選択範囲をブロックコメント化",
|
||||
formatSelectionSql: "選択した SQL をフォーマット",
|
||||
compressSelectionSql: "選択した SQL を圧縮",
|
||||
folding: "折りたたみ",
|
||||
toggleFold: "折りたたみの切り替え",
|
||||
foldAll: "すべて折りたたむ",
|
||||
unfoldAll: "すべて展開",
|
||||
sendToAi: "AIに送信",
|
||||
uppercaseSelection: "大文字に変換",
|
||||
lowercaseSelection: "小文字に変換",
|
||||
@@ -7683,6 +7689,8 @@ export default withEnglishFallback({
|
||||
intentionUnqualifyIdentifier: "修飾を解除",
|
||||
intentionBatchQualifyIdentifiers: "識別子を一括修飾",
|
||||
shortcutToggleFold: "折りたたみの切り替え",
|
||||
shortcutFoldAll: "すべて折りたたむ",
|
||||
shortcutUnfoldAll: "すべて展開",
|
||||
shortcutScopeGlobal: "グローバル",
|
||||
shortcutScopeEditor: "SQLエディタ",
|
||||
shortcutScopeGrid: "データグリッド",
|
||||
|
||||
@@ -391,6 +391,8 @@ export default withEnglishFallback({
|
||||
formatSqlFailed: "SQL 정렬에 실패했습니다",
|
||||
formatAutoDetectFailed: "선택한 내용을 인식하거나 포맷할 수 없습니다",
|
||||
compressSql: "SQL 압축",
|
||||
foldAll: "모두 접기",
|
||||
unfoldAll: "모두 펼치기",
|
||||
keywordCaseLower: "SQL 키워드 소문자 사용",
|
||||
keywordCaseUpper: "SQL 키워드 대문자 사용",
|
||||
sqlSemanticDiagnosticsToggleOn: "SQL 의미 진단: 켜짐 (클릭하여 끄기)",
|
||||
@@ -1608,6 +1610,10 @@ export default withEnglishFallback({
|
||||
blockCommentSelection: "선택 항목 블록 주석 처리",
|
||||
formatSelectionSql: "선택한 SQL 서식 지정",
|
||||
compressSelectionSql: "선택한 SQL 압축",
|
||||
folding: "코드 접기",
|
||||
toggleFold: "접기/펼치기",
|
||||
foldAll: "모두 접기",
|
||||
unfoldAll: "모두 펼치기",
|
||||
cutSelection: "선택 영역 잘라내기",
|
||||
pasteFromClipboard: "붙여넣기",
|
||||
pasteRestoringSourceSql: "붙여넣고 소스 SQL 복원",
|
||||
@@ -7939,6 +7945,9 @@ export default withEnglishFallback({
|
||||
shortcutUppercaseSelection: "선택 영역을 대문자로 변환",
|
||||
shortcutLowercaseSelection: "선택 영역을 소문자로 변환",
|
||||
shortcutExPasteSqlInCondition: "ExPaste: IN 조건으로 붙여넣기",
|
||||
shortcutToggleFold: "접기/펼치기",
|
||||
shortcutFoldAll: "모두 접기",
|
||||
shortcutUnfoldAll: "모두 펼치기",
|
||||
csvQuoteMode: "CSV 필드 따옴표",
|
||||
csvQuoteModeDescription: "CSV 내보내기 시 필드에 큰따옴표를 사용하는 방식을 선택합니다.",
|
||||
csvQuoteModeAll: "모든 필드",
|
||||
|
||||
@@ -383,6 +383,8 @@ export default withEnglishFallback({
|
||||
formatSqlFailed: "Falha ao formatar SQL",
|
||||
formatAutoDetectFailed: "Não foi possível reconhecer ou formatar o conteúdo selecionado",
|
||||
compressSql: "Comprimir SQL",
|
||||
foldAll: "Recolher tudo",
|
||||
unfoldAll: "Expandir tudo",
|
||||
keywordCaseLower: "Usar palavras-chave SQL em minúsculas",
|
||||
keywordCaseUpper: "Usar palavras-chave SQL em maiúsculas",
|
||||
sqlSemanticDiagnosticsToggleOn: "Diagnóstico semântico de SQL: ativado (clique para desativar)",
|
||||
@@ -1682,6 +1684,10 @@ export default withEnglishFallback({
|
||||
blockCommentSelection: "Comentário de bloco na seleção",
|
||||
formatSelectionSql: "Formatar SQL selecionado",
|
||||
compressSelectionSql: "Compactar SQL selecionado",
|
||||
folding: "Dobragem de código",
|
||||
toggleFold: "Recolher/expandir código",
|
||||
foldAll: "Recolher tudo",
|
||||
unfoldAll: "Expandir tudo",
|
||||
sendToAi: "Enviar para IA",
|
||||
uppercaseSelection: "Converter para maiúsculas",
|
||||
lowercaseSelection: "Converter para minúsculas",
|
||||
@@ -7687,6 +7693,8 @@ export default withEnglishFallback({
|
||||
intentionUnqualifyIdentifier: "Remover qualificação",
|
||||
intentionBatchQualifyIdentifiers: "Qualificar identificadores em lote",
|
||||
shortcutToggleFold: "Recolher/expandir código",
|
||||
shortcutFoldAll: "Recolher tudo",
|
||||
shortcutUnfoldAll: "Expandir tudo",
|
||||
shortcutScopeGlobal: "Global",
|
||||
shortcutScopeEditor: "Editor SQL",
|
||||
shortcutScopeGrid: "Grade de dados",
|
||||
|
||||
@@ -365,6 +365,8 @@ export default withEnglishFallback({
|
||||
formatSqlFailed: "Не удалось отформатировать SQL",
|
||||
formatAutoDetectFailed: "Не удаётся распознать или отформатировать выделенный фрагмент",
|
||||
compressSql: "Сжать SQL",
|
||||
foldAll: "Свернуть все",
|
||||
unfoldAll: "Развернуть все",
|
||||
keywordCaseLower: "Ключевые слова SQL в нижнем регистре",
|
||||
keywordCaseUpper: "Ключевые слова SQL в верхнем регистре",
|
||||
sqlSemanticDiagnosticsToggleOn: "Семантическая диагностика SQL: вкл. (нажмите, чтобы отключить)",
|
||||
@@ -1691,6 +1693,10 @@ export default withEnglishFallback({
|
||||
blockCommentSelection: "Блочный комментарий выделенного",
|
||||
formatSelectionSql: "Форматировать выделенный SQL",
|
||||
compressSelectionSql: "Сжать выделенный SQL",
|
||||
folding: "Сворачивание",
|
||||
toggleFold: "Свернуть/развернуть",
|
||||
foldAll: "Свернуть все",
|
||||
unfoldAll: "Развернуть все",
|
||||
cutSelection: "Вырезать выделенное",
|
||||
pasteFromClipboard: "Вставить",
|
||||
pasteRestoringSourceSql: "Вставить и восстановить SQL из кода",
|
||||
@@ -8938,6 +8944,8 @@ export default withEnglishFallback({
|
||||
intentionUnqualifyIdentifier: "Убрать уточнение идентификатора",
|
||||
intentionBatchQualifyIdentifiers: "Пакетное уточнение идентификаторов",
|
||||
shortcutToggleFold: "Свернуть/развернуть",
|
||||
shortcutFoldAll: "Свернуть все",
|
||||
shortcutUnfoldAll: "Развернуть все",
|
||||
shortcutScopeGlobal: "Глобально",
|
||||
shortcutScopeEditor: "SQL-редактор",
|
||||
shortcutScopeGrid: "Таблица данных",
|
||||
|
||||
@@ -219,6 +219,8 @@ export default withEnglishFallback({
|
||||
formatSqlFailed: "SQL biçimlendirilemedi",
|
||||
formatAutoDetectFailed: "Seçilen içerik tanınamıyor veya biçimlendirilemiyor",
|
||||
compressSql: "SQL'i Sıkıştır",
|
||||
foldAll: "Tümünü daralt",
|
||||
unfoldAll: "Tümünü genişlet",
|
||||
keywordCaseLower: "SQL anahtar sözcüklerini küçük harf yap",
|
||||
keywordCaseUpper: "SQL anahtar sözcüklerini büyük harf yap",
|
||||
sqlSemanticDiagnosticsToggleOn: "SQL anlamsal tanılama: Açık (kapatmak için tıklayın)",
|
||||
@@ -1486,6 +1488,10 @@ export default withEnglishFallback({
|
||||
blockCommentSelection: "Seçimi blok yorum yap",
|
||||
formatSelectionSql: "Seçili SQL'i biçimlendir",
|
||||
compressSelectionSql: "Seçili SQL'i sıkıştır",
|
||||
folding: "Kod Katlama",
|
||||
toggleFold: "Katlamayı aç/kapat",
|
||||
foldAll: "Tümünü daralt",
|
||||
unfoldAll: "Tümünü genişlet",
|
||||
cutSelection: "Seçimi kes",
|
||||
pasteFromClipboard: "Yapıştır",
|
||||
pasteRestoringSourceSql: "Yapıştır ve kaynak SQL'i geri yükle",
|
||||
@@ -7612,6 +7618,8 @@ export default withEnglishFallback({
|
||||
intentionUnqualifyIdentifier: "Tanımlayıcı Nitelemesini Kaldır",
|
||||
intentionBatchQualifyIdentifiers: "Tanımlayıcıları Toplu Nitele",
|
||||
shortcutToggleFold: "Katlamayı aç/kapat",
|
||||
shortcutFoldAll: "Tümünü daralt",
|
||||
shortcutUnfoldAll: "Tümünü genişlet",
|
||||
shortcutScopeGlobal: "Genel",
|
||||
shortcutScopeEditor: "SQL düzenleyici",
|
||||
shortcutScopeGrid: "Veri tablosu",
|
||||
|
||||
@@ -332,6 +332,8 @@ export default withEnglishFallback({
|
||||
formatSqlFailed: "SQL 格式化失败",
|
||||
formatAutoDetectFailed: "无法识别或格式化所选内容",
|
||||
compressSql: "压缩 SQL",
|
||||
foldAll: "全部折叠",
|
||||
unfoldAll: "全部展开",
|
||||
keywordCaseLower: "使用小写 SQL 关键字",
|
||||
keywordCaseUpper: "使用大写 SQL 关键字",
|
||||
sqlSemanticDiagnosticsToggleOn: "SQL 语义诊断:已开启(点击关闭)",
|
||||
@@ -1719,6 +1721,10 @@ export default withEnglishFallback({
|
||||
blockCommentSelection: "块注释选中内容",
|
||||
formatSelectionSql: "格式化选中SQL",
|
||||
compressSelectionSql: "压缩选中SQL",
|
||||
folding: "折叠",
|
||||
toggleFold: "切换折叠",
|
||||
foldAll: "全部折叠",
|
||||
unfoldAll: "全部展开",
|
||||
cutSelection: "剪切选中内容",
|
||||
pasteFromClipboard: "粘贴",
|
||||
pasteRestoringSourceSql: "粘贴并还原源码 SQL",
|
||||
@@ -8610,6 +8616,8 @@ export default withEnglishFallback({
|
||||
intentionUnqualifyIdentifier: "取消限定",
|
||||
intentionBatchQualifyIdentifiers: "批量限定标识符",
|
||||
shortcutToggleFold: "切换折叠",
|
||||
shortcutFoldAll: "全部折叠",
|
||||
shortcutUnfoldAll: "全部展开",
|
||||
shortcutScopeGlobal: "全局",
|
||||
shortcutScopeEditor: "SQL 编辑器",
|
||||
shortcutScopeGrid: "数据表格",
|
||||
|
||||
@@ -388,6 +388,8 @@ export default withEnglishFallback({
|
||||
formatSqlFailed: "SQL 格式化失敗",
|
||||
formatAutoDetectFailed: "無法識別或格式化所選內容",
|
||||
compressSql: "壓縮 SQL",
|
||||
foldAll: "全部折疊",
|
||||
unfoldAll: "全部展開",
|
||||
keywordCaseLower: "使用小寫 SQL 關鍵字",
|
||||
keywordCaseUpper: "使用大寫 SQL 關鍵字",
|
||||
sqlSemanticDiagnosticsToggleOn: "SQL 語意診斷:已開啟(點擊關閉)",
|
||||
@@ -1685,6 +1687,10 @@ export default withEnglishFallback({
|
||||
blockCommentSelection: "區塊註解選取內容",
|
||||
formatSelectionSql: "格式化選取的 SQL",
|
||||
compressSelectionSql: "壓縮選取的 SQL",
|
||||
folding: "折疊",
|
||||
toggleFold: "切換折疊",
|
||||
foldAll: "全部折疊",
|
||||
unfoldAll: "全部展開",
|
||||
sendToAi: "傳送至 AI",
|
||||
uppercaseSelection: "轉為大寫",
|
||||
lowercaseSelection: "轉為小寫",
|
||||
@@ -7012,6 +7018,8 @@ export default withEnglishFallback({
|
||||
intentionUnqualifyIdentifier: "取消限定",
|
||||
intentionBatchQualifyIdentifiers: "批量限定識別碼",
|
||||
shortcutToggleFold: "切換折疊",
|
||||
shortcutFoldAll: "全部折疊",
|
||||
shortcutUnfoldAll: "全部展開",
|
||||
shortcutScopeGlobal: "全域",
|
||||
shortcutScopeEditor: "SQL 編輯器",
|
||||
shortcutScopeGrid: "資料表格",
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import type { ShortcutSettings } from "@/lib/editor/shortcutRegistry";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const macNavigator = {
|
||||
maxTouchPoints: 0,
|
||||
platform: "MacIntel",
|
||||
userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Version/18.6 Safari/605.1.15",
|
||||
vendor: "Apple Computer, Inc.",
|
||||
};
|
||||
|
||||
async function createHarness(overrides?: Partial<ShortcutSettings>) {
|
||||
vi.stubGlobal("navigator", macNavigator);
|
||||
vi.resetModules();
|
||||
const [{ EditorState, Prec }, { EditorView, keymap, runScopeHandlers }, { sql }, { foldAll, foldedRanges, foldKeymap, unfoldAll }, { normalizeShortcutSettings }, { createQueryEditorFoldShortcutBindings, foldKeymapWithoutAllBindings }] = await Promise.all([
|
||||
import("@codemirror/state"),
|
||||
import("@codemirror/view"),
|
||||
import("@codemirror/lang-sql"),
|
||||
import("@codemirror/language"),
|
||||
import("@/lib/editor/shortcutRegistry"),
|
||||
import("@/lib/editor/queryEditorFoldKeymap"),
|
||||
]);
|
||||
const shortcuts = normalizeShortcutSettings(overrides, "MacIntel");
|
||||
const root = document.createElement("div");
|
||||
document.body.append(root);
|
||||
const view = new EditorView({
|
||||
parent: root,
|
||||
state: EditorState.create({
|
||||
doc: "/* first\nbody\n*/\n\n/* second\nbody\n*/",
|
||||
extensions: [sql(), keymap.of(foldKeymapWithoutAllBindings(foldKeymap, foldAll, unfoldAll)), Prec.high(keymap.of(createQueryEditorFoldShortcutBindings(shortcuts, foldAll, unfoldAll)))],
|
||||
}),
|
||||
});
|
||||
const press = (key: string, options: KeyboardEventInit) => runScopeHandlers(view, new KeyboardEvent("keydown", { key, code: key === "[" ? "BracketLeft" : "BracketRight", ...options }), "editor");
|
||||
const foldedCount = () => {
|
||||
let count = 0;
|
||||
foldedRanges(view.state).between(0, view.state.doc.length, () => count++);
|
||||
return count;
|
||||
};
|
||||
return { foldedCount, press, root, shortcuts, view };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("QueryEditor fold keymap on macOS", () => {
|
||||
it("keeps fold-current separate from the configurable fold-all defaults", async () => {
|
||||
const { foldedCount, press, shortcuts, view } = await createHarness();
|
||||
|
||||
expect(shortcuts).toMatchObject({ foldAll: "Ctrl+Alt+[", unfoldAll: "Ctrl+Alt+]" });
|
||||
expect(press("[", { metaKey: true, altKey: true })).toBe(true);
|
||||
expect(foldedCount()).toBe(1);
|
||||
expect(press("]", { metaKey: true, altKey: true })).toBe(true);
|
||||
expect(foldedCount()).toBe(0);
|
||||
expect(press("[", { ctrlKey: true, altKey: true })).toBe(true);
|
||||
expect(foldedCount()).toBe(2);
|
||||
expect(press("]", { ctrlKey: true, altKey: true })).toBe(true);
|
||||
expect(foldedCount()).toBe(0);
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
it("does not retain CodeMirror fold-all keys when the settings are cleared", async () => {
|
||||
const { foldedCount, press, view } = await createHarness({ foldAll: "", unfoldAll: "" });
|
||||
|
||||
expect(press("[", { ctrlKey: true, altKey: true })).toBe(false);
|
||||
expect(press("]", { ctrlKey: true, altKey: true })).toBe(false);
|
||||
expect(foldedCount()).toBe(0);
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
it("uses rebound fold-all keys without retaining the previous defaults", async () => {
|
||||
const { foldedCount, press, view } = await createHarness({ foldAll: "Ctrl+Shift+[", unfoldAll: "Ctrl+Shift+]" });
|
||||
|
||||
expect(press("[", { ctrlKey: true, altKey: true })).toBe(false);
|
||||
expect(press("[", { ctrlKey: true, shiftKey: true })).toBe(true);
|
||||
expect(foldedCount()).toBe(2);
|
||||
expect(press("]", { ctrlKey: true, altKey: true })).toBe(false);
|
||||
expect(press("]", { ctrlKey: true, shiftKey: true })).toBe(true);
|
||||
expect(foldedCount()).toBe(0);
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
DEFAULT_SHORTCUT_SETTINGS,
|
||||
findCrossScopeShortcutConflicts,
|
||||
findShortcutConflict,
|
||||
foldAllDefaultShortcut,
|
||||
formatShortcut,
|
||||
gotoLineDefaultShortcut,
|
||||
isReservedShortcut,
|
||||
@@ -42,6 +43,8 @@ describe("shortcutRegistry editor actions", () => {
|
||||
"lowercaseSelection",
|
||||
"exPasteSqlInCondition",
|
||||
"toggleFold",
|
||||
"foldAll",
|
||||
"unfoldAll",
|
||||
];
|
||||
const sidebarShortcutActionIds: ShortcutActionId[] = ["copySidebarSelection", "pasteSidebarSelection", "editSidebarConnection", "disconnectSidebarConnection", "viewTableDdl"];
|
||||
|
||||
@@ -291,6 +294,18 @@ describe("shortcutRegistry editor actions", () => {
|
||||
expect(shortcuts.lowercaseSelection).toBe("Shift+Alt+L");
|
||||
expect(shortcuts.exPasteSqlInCondition).toBe("");
|
||||
expect(shortcuts.toggleFold).toBe("Mod+.");
|
||||
expect(shortcuts.foldAll).toBe(foldAllDefaultShortcut("foldAll"));
|
||||
expect(shortcuts.unfoldAll).toBe(foldAllDefaultShortcut("unfoldAll"));
|
||||
});
|
||||
|
||||
it("uses platform-safe fold-all defaults and migrates the colliding defaults", () => {
|
||||
expect(foldAllDefaultShortcut("foldAll", "MacIntel")).toBe("Ctrl+Alt+[");
|
||||
expect(foldAllDefaultShortcut("unfoldAll", "MacIntel")).toBe("Ctrl+Alt+]");
|
||||
expect(foldAllDefaultShortcut("foldAll", "Win32")).toBe("Shift+Alt+[");
|
||||
expect(foldAllDefaultShortcut("unfoldAll", "Linux x86_64")).toBe("Shift+Alt+]");
|
||||
expect(normalizeShortcutSettings({ foldAll: "Mod+Alt+[", unfoldAll: "Mod+Alt+]" }, "MacIntel")).toMatchObject({ foldAll: "Ctrl+Alt+[", unfoldAll: "Ctrl+Alt+]" });
|
||||
expect(normalizeShortcutSettings({ foldAll: "Ctrl+Alt+[", unfoldAll: "Ctrl+Alt+]" }, "Win32")).toMatchObject({ foldAll: "Shift+Alt+[", unfoldAll: "Shift+Alt+]" });
|
||||
expect(normalizeShortcutSettings({ foldAll: "", unfoldAll: "" }, "Win32")).toMatchObject({ foldAll: "", unfoldAll: "" });
|
||||
});
|
||||
|
||||
it("registers IntelliJ-style extend selection as a configurable editor shortcut", () => {
|
||||
@@ -549,6 +564,8 @@ describe("shortcutRegistry editor actions", () => {
|
||||
["selectAllSelectionOccurrences", "Ctrl+Alt+Shift+J"],
|
||||
["toggleAiPanel", "Ctrl+Alt+I"],
|
||||
["gotoLine", "Mod+G"],
|
||||
["foldAll", "Shift+Alt+["],
|
||||
["unfoldAll", "Shift+Alt+]"],
|
||||
];
|
||||
|
||||
it("flags combinations that are another platform's default for the same action", () => {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { Command, KeyBinding } from "@codemirror/view";
|
||||
import { shortcutToCodeMirrorKey, type ShortcutSettings } from "@/lib/editor/shortcutRegistry";
|
||||
|
||||
type FoldShortcuts = Pick<ShortcutSettings, "foldAll" | "unfoldAll">;
|
||||
|
||||
export function foldKeymapWithoutAllBindings(foldKeymap: readonly KeyBinding[], foldAll: Command, unfoldAll: Command): KeyBinding[] {
|
||||
return foldKeymap.filter((binding) => binding.run !== foldAll && binding.run !== unfoldAll);
|
||||
}
|
||||
|
||||
export function createQueryEditorFoldShortcutBindings(shortcuts: FoldShortcuts, foldAll: Command, unfoldAll: Command): KeyBinding[] {
|
||||
return [...(shortcuts.foldAll ? [{ key: shortcutToCodeMirrorKey(shortcuts.foldAll), preventDefault: true, run: foldAll }] : []), ...(shortcuts.unfoldAll ? [{ key: shortcutToCodeMirrorKey(shortcuts.unfoldAll), preventDefault: true, run: unfoldAll }] : [])];
|
||||
}
|
||||
@@ -32,6 +32,8 @@ export type ShortcutActionId =
|
||||
| "convertNamingStyle"
|
||||
| "exPasteSqlInCondition"
|
||||
| "toggleFold"
|
||||
| "foldAll"
|
||||
| "unfoldAll"
|
||||
| "editTableStructure"
|
||||
| "copyCurrentRow"
|
||||
| "deleteCurrentRow"
|
||||
@@ -138,6 +140,11 @@ export function gotoLineDefaultShortcut(platform = globalThis.navigator?.platfor
|
||||
return isMacShortcutPlatform(platform) ? "Mod+Alt+G" : "Mod+G";
|
||||
}
|
||||
|
||||
export function foldAllDefaultShortcut(actionId: "foldAll" | "unfoldAll", platform = globalThis.navigator?.platform || ""): string {
|
||||
const key = actionId === "foldAll" ? "[" : "]";
|
||||
return `${isMacShortcutPlatform(platform) ? "Ctrl+Alt" : "Shift+Alt"}+${key}`;
|
||||
}
|
||||
|
||||
const PLATFORM_DEFAULT_SHORTCUTS: Partial<Record<ShortcutActionId, ReadonlySet<string>>> = {
|
||||
closeOtherTabs: new Set(["Alt+Mod+W", "Shift+Alt+W"]),
|
||||
navigateTabHistoryBack: new Set(["Ctrl+Alt+ArrowLeft", "Mod+Alt+ArrowLeft"]),
|
||||
@@ -146,6 +153,8 @@ const PLATFORM_DEFAULT_SHORTCUTS: Partial<Record<ShortcutActionId, ReadonlySet<s
|
||||
selectAllSelectionOccurrences: new Set(["Ctrl+Mod+G", "Ctrl+Alt+Shift+J"]),
|
||||
toggleAiPanel: new Set(["Ctrl+Mod+I", "Ctrl+Alt+I"]),
|
||||
gotoLine: new Set(["Mod+G", "Mod+Alt+G"]),
|
||||
foldAll: new Set(["Mod+Alt+[", "Ctrl+Alt+[", "Shift+Alt+["]),
|
||||
unfoldAll: new Set(["Mod+Alt+]", "Ctrl+Alt+]", "Shift+Alt+]"]),
|
||||
};
|
||||
const LEGACY_CLOSE_TAB_DEFAULT = "Meta+W";
|
||||
const LEGACY_COPY_CURRENT_ROW_DEFAULT = "Mod+D";
|
||||
@@ -339,6 +348,18 @@ export const SHORTCUT_DEFINITIONS: ShortcutDefinition[] = [
|
||||
scope: "editor",
|
||||
defaultShortcut: "Mod+.",
|
||||
},
|
||||
{
|
||||
id: "foldAll",
|
||||
labelKey: "settings.shortcutFoldAll",
|
||||
scope: "editor",
|
||||
defaultShortcut: foldAllDefaultShortcut("foldAll"),
|
||||
},
|
||||
{
|
||||
id: "unfoldAll",
|
||||
labelKey: "settings.shortcutUnfoldAll",
|
||||
scope: "editor",
|
||||
defaultShortcut: foldAllDefaultShortcut("unfoldAll"),
|
||||
},
|
||||
{
|
||||
id: "editTableStructure",
|
||||
labelKey: "settings.shortcutEditTableStructure",
|
||||
@@ -686,6 +707,7 @@ function shortcutDefaultForPlatform(definition: ShortcutDefinition, platform: st
|
||||
if (definition.id === "navigateTabHistoryBack") return tabNavigationHistoryDefaultShortcut("back", platform);
|
||||
if (definition.id === "navigateTabHistoryForward") return tabNavigationHistoryDefaultShortcut("forward", platform);
|
||||
if (definition.id === "toggleAiPanel") return toggleAiPanelDefaultShortcut(platform);
|
||||
if (definition.id === "foldAll" || definition.id === "unfoldAll") return foldAllDefaultShortcut(definition.id, platform);
|
||||
return definition.defaultShortcut;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user