diff --git a/apps/desktop/src/components/editor/EditorSearchPanel.vue b/apps/desktop/src/components/editor/EditorSearchPanel.vue index 8418636a50..9ed4127775 100644 --- a/apps/desktop/src/components/editor/EditorSearchPanel.vue +++ b/apps/desktop/src/components/editor/EditorSearchPanel.vue @@ -8,6 +8,7 @@ import { ChevronUp, ChevronDown, ChevronRight, TextSelect, X } from "@lucide/vue import { collectEditorSearchMatches, countEditorSearchMatches, createEditorSearchQuery, replaceEditorSearchMatches, type EditorSearchMatch } from "@/lib/editor/editorSearchQuery"; import { appendSearchMatchSelection, findSearchMatch, isSearchAddSelectionModifier, selectionRangesForSearchMatches, type EditorSearchSelectionDirection } from "@/lib/editor/editorSearchSelection"; import { useSettingsStore } from "@/stores/settingsStore"; +import { vNamingStyleSupport } from "@/directives/vNamingStyleSupport"; const props = defineProps<{ view: EditorView | null; @@ -501,6 +502,7 @@ defineExpose({ import { ref, onMounted, onBeforeUnmount, onActivated, onDeactivated, watch, shallowRef, computed, nextTick } from "vue"; -import { AlignLeft, Camera, CaseLower, CaseUpper, ClipboardPaste, Code2, Download, Eye, FileCode, MessageSquareText, Minimize2, Pencil, PencilRuler, Play, Copy, List, Scissors, Search, Sparkles, Table2, TextSelect, Trash2 } from "@lucide/vue"; +import { AlignLeft, Camera, CaseLower, CaseSensitive, CaseUpper, ClipboardPaste, Code2, Download, Eye, FileCode, MessageSquareText, Minimize2, Pencil, PencilRuler, Play, Copy, List, Scissors, Search, Sparkles, Table2, TextSelect, Trash2 } from "@lucide/vue"; import { useI18n } from "vue-i18n"; import type { Completion, CompletionContext } from "@codemirror/autocomplete"; import { Transaction, StateEffect } from "@codemirror/state"; @@ -32,6 +32,7 @@ import { createSqlSignatureTooltipDom } from "@/lib/editor/sqlSignatureTooltip"; import { buildSqlInConditionFromPasteSource, insertTextForSqlInCondition } from "@/lib/sql/sqlInListPaste"; import { resolveSqlSingleQuoteKeyAction } from "@/lib/sql/sqlQuoteCaret"; import { convertSqlSelectionCase, type SqlSelectionCaseMode } from "@/lib/sql/sqlSelectionCase"; +import { convertToNextNamingStyle } from "@/lib/naming/namingStyleConverter"; import { formatMongoShellText } from "@/lib/mongo/mongoFormatter"; import { detectAndFormatElasticsearchRequests } from "@/lib/elasticsearch/elasticsearchFormatter"; import { useConnectionStore, COMPLETION_METADATA_CONCURRENCY } from "@/stores/connectionStore"; @@ -1598,6 +1599,35 @@ function convertSelectedSqlCase(mode: SqlSelectionCaseMode): boolean { return false; } +function convertSelectedNamingStyle(): boolean { + const currentView = view.value; + const EditorSelection = codeMirrorEditorSelection; + if (!currentView || !EditorSelection) return false; + + const state = currentView.state; + const transaction = state.changeByRange((range) => { + if (range.empty) return { range }; + + const selectedText = state.doc.sliceString(range.from, range.to); + const result = convertToNextNamingStyle(selectedText); + return { + changes: { from: range.from, to: range.to, insert: result.text }, + range: EditorSelection.range(range.from, range.from + result.text.length), + }; + }); + + if (!transaction.changes.empty) { + currentView.dispatch({ + ...transaction, + scrollIntoView: true, + userEvent: "input", + }); + focusEditor(); + return true; + } + return false; +} + async function pasteClipboardAsSqlInCondition(): Promise { if (!supportsSqlInListPaste(props.databaseType)) return false; if (props.readOnly) return false; @@ -1950,6 +1980,13 @@ const contextMenuItems = computed(() => { icon: CaseLower, shortcut: shortcuts.lowercaseSelection, }, + { + label: t("editor.contextMenu.convertNamingStyle"), + action: convertSelectedNamingStyle, + disabled: !canCopySelectedSql.value, + icon: CaseSensitive, + shortcut: shortcuts.convertNamingStyle, + }, { label: t("editor.contextMenu.delimitedList"), action: openDelimitedListDialog, @@ -2136,6 +2173,7 @@ function runKeymapExtension(codeMirrorKeymap: (typeof import("@codemirror/view") ...binding(shortcuts.selectAllSelectionOccurrences, selectAllQueryEditorSelectionOccurrences), ...createQueryEditorSelectionCaseShortcutBindings(shortcuts.uppercaseSelection, () => convertSelectedSqlCase("upper")), ...createQueryEditorSelectionCaseShortcutBindings(shortcuts.lowercaseSelection, () => convertSelectedSqlCase("lower")), + ...createQueryEditorSelectionCaseShortcutBindings(shortcuts.convertNamingStyle, () => convertSelectedNamingStyle()), ...binding(shortcuts.toggleLineComment, (view) => codeMirrorToggleLineComment?.(view) ?? false), ...binding(shortcuts.toggleBlockComment, (view) => { if (!supportsQueryEditorBlockComments(props.databaseType)) return false; diff --git a/apps/desktop/src/components/grid/DataGridSearchBar.vue b/apps/desktop/src/components/grid/DataGridSearchBar.vue index bf3a1844c0..a7a912255e 100644 --- a/apps/desktop/src/components/grid/DataGridSearchBar.vue +++ b/apps/desktop/src/components/grid/DataGridSearchBar.vue @@ -2,6 +2,7 @@ import { ref } from "vue"; import { ChevronDown, ChevronUp, Search, X } from "@lucide/vue"; import { useI18n } from "vue-i18n"; +import { vNamingStyleSupport } from "@/directives/vNamingStyleSupport"; const { t } = useI18n(); @@ -52,6 +53,7 @@ defineExpose({ ({ + shortcuts: {} as Record, +})); + +vi.mock("@/stores/settingsStore", () => ({ + useSettingsStore: () => ({ editorSettings: { shortcuts: shortcutState.shortcuts } }), +})); + +function mountInput(value: string): HTMLInputElement { + const input = document.createElement("input"); + input.type = "text"; + document.body.appendChild(input); + vNamingStyleSupport.mounted!(input, {} as any, {} as any, null as any); + input.value = value; + input.focus(); + return input; +} + +function unmountInput(input: HTMLInputElement): void { + vNamingStyleSupport.unmounted!(input, {} as any, {} as any, null as any); + document.body.removeChild(input); +} + +function pressNamingStyleShortcut(input: HTMLInputElement, overrides: Partial = {}): KeyboardEvent { + const event = new KeyboardEvent("keydown", { + key: "c", + code: "KeyC", + shiftKey: true, + altKey: true, + bubbles: true, + cancelable: true, + ...overrides, + }); + input.dispatchEvent(event); + return event; +} + +describe("vNamingStyleSupport directive", () => { + it("converts selected text on Shift+Alt+C", () => { + const input = mountInput("user_name"); + input.setSelectionRange(0, 9); + + pressNamingStyleShortcut(input); + + // snake_case → SCREAMING_SNAKE_CASE + expect(input.value).toBe("USER_NAME"); + + unmountInput(input); + }); + + it("converts entire input when no selection", () => { + const input = mountInput("user_name"); + + pressNamingStyleShortcut(input); + + expect(input.value).toBe("USER_NAME"); + + unmountInput(input); + }); + + it("cycles through naming styles", () => { + const input = mountInput("userName"); + + // camelCase → PascalCase + pressNamingStyleShortcut(input); + expect(input.value).toBe("UserName"); + + // PascalCase → snake_case + pressNamingStyleShortcut(input); + expect(input.value).toBe("user_name"); + + // snake_case → SCREAMING_SNAKE_CASE + pressNamingStyleShortcut(input); + expect(input.value).toBe("USER_NAME"); + + // SCREAMING_SNAKE_CASE → kebab-case + pressNamingStyleShortcut(input); + expect(input.value).toBe("user-name"); + + // kebab-case → camelCase + pressNamingStyleShortcut(input); + expect(input.value).toBe("userName"); + + unmountInput(input); + }); + + it("matches the physical key on macOS composed characters (⌥⇧C → Ç)", () => { + const input = mountInput("userName"); + + const event = pressNamingStyleShortcut(input, { key: "Ç" }); + + expect(input.value).toBe("UserName"); + expect(event.defaultPrevented).toBe(true); + + unmountInput(input); + }); + + it("follows the shortcut configured in settings instead of the default", () => { + shortcutState.shortcuts = { convertNamingStyle: "Shift+Alt+N" }; + try { + const input = mountInput("userName"); + + // Default Shift+Alt+C no longer triggers. + const defaultEvent = pressNamingStyleShortcut(input); + expect(input.value).toBe("userName"); + expect(defaultEvent.defaultPrevented).toBe(false); + + // The remapped Shift+Alt+N does. + const remappedEvent = pressNamingStyleShortcut(input, { key: "n", code: "KeyN" }); + expect(input.value).toBe("UserName"); + expect(remappedEvent.defaultPrevented).toBe(true); + + unmountInput(input); + } finally { + shortcutState.shortcuts = {}; + } + }); + + it("does not trigger when Ctrl or Meta is also held", () => { + const input = mountInput("userName"); + + const withCtrl = pressNamingStyleShortcut(input, { ctrlKey: true }); + expect(input.value).toBe("userName"); + expect(withCtrl.defaultPrevented).toBe(false); + + const withMeta = pressNamingStyleShortcut(input, { metaKey: true }); + expect(input.value).toBe("userName"); + expect(withMeta.defaultPrevented).toBe(false); + + unmountInput(input); + }); + + it("lets the keystroke through when the content is not a single identifier", () => { + const input = mountInput("price - discount"); + + const event = pressNamingStyleShortcut(input); + + expect(input.value).toBe("price - discount"); + expect(event.defaultPrevented).toBe(false); + + unmountInput(input); + }); + + it("preserves surrounding whitespace when converting the whole input", () => { + const input = mountInput(" userName "); + + pressNamingStyleShortcut(input); + + expect(input.value).toBe(" UserName "); + + unmountInput(input); + }); +}); diff --git a/apps/desktop/src/directives/vNamingStyleSupport.ts b/apps/desktop/src/directives/vNamingStyleSupport.ts new file mode 100644 index 0000000000..d425f1fd11 --- /dev/null +++ b/apps/desktop/src/directives/vNamingStyleSupport.ts @@ -0,0 +1,51 @@ +import type { Directive } from "vue"; +import { isConvertNamingStyleShortcut } from "@/lib/editor/keyboardShortcuts"; +import { convertToNextNamingStyle } from "@/lib/naming/namingStyleConverter"; +import { useSettingsStore } from "@/stores/settingsStore"; + +function handleKeydown(event: KeyboardEvent): void { + if (event.isComposing) return; + + // Match against the user-configured shortcut so settings changes apply + // immediately; matchesShortcut uses the physical-key (event.code) fallback + // so macOS Option+letter composed keys (⌥⇧C → "Ç") still match, and its + // strict modifier check rejects combos with extra Ctrl/Meta held. + const shortcuts = useSettingsStore().editorSettings.shortcuts; + if (!isConvertNamingStyleShortcut(event, shortcuts)) return; + + const target = event.target as HTMLInputElement | HTMLTextAreaElement; + const value = target.value; + const start = target.selectionStart ?? 0; + const end = target.selectionEnd ?? 0; + const source = start === end ? value : value.slice(start, end); + const result = convertToNextNamingStyle(source); + + // No identifier-like content to convert: leave the keystroke to the + // browser instead of swallowing it. + if (result.text === source) return; + + event.preventDefault(); + event.stopPropagation(); + + if (start === end) { + // No selection - convert entire content + target.value = result.text; + target.setSelectionRange(0, result.text.length); + } else { + // Convert selected text + target.value = value.slice(0, start) + result.text + value.slice(end); + target.setSelectionRange(start + result.text.length, start + result.text.length); + } + + // Trigger input event so v-model updates + target.dispatchEvent(new Event("input", { bubbles: true })); +} + +export const vNamingStyleSupport: Directive = { + mounted(el) { + el.addEventListener("keydown", handleKeydown as EventListener); + }, + unmounted(el) { + el.removeEventListener("keydown", handleKeydown as EventListener); + }, +}; diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts index aae358608d..e094e853be 100644 --- a/apps/desktop/src/i18n/locales/en.ts +++ b/apps/desktop/src/i18n/locales/en.ts @@ -1375,6 +1375,7 @@ export default { sendToAi: "Send to AI", uppercaseSelection: "Convert to uppercase", lowercaseSelection: "Convert to lowercase", + convertNamingStyle: "Toggle naming style", delimitedList: "Convert to delimited list", addNextSelectionOccurrence: "Add next occurrence", selectAllSelectionOccurrences: "Select all occurrences", @@ -7311,6 +7312,7 @@ export default { changelogSectionRemoved: "Removed", shortcutUppercaseSelection: "Convert selection to uppercase", shortcutLowercaseSelection: "Convert selection to lowercase", + shortcutConvertNamingStyle: "Toggle naming style", shortcutExPasteSqlInCondition: "ExPaste: paste as IN condition", }, driverStore: { diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts index cc2014cb10..b776ff29b4 100644 --- a/apps/desktop/src/i18n/locales/es.ts +++ b/apps/desktop/src/i18n/locales/es.ts @@ -1357,6 +1357,7 @@ export default withEnglishFallback({ cutSelection: "Cortar selección", pasteFromClipboard: "Pegar", pasteClipboardReadFailed: "Error al leer el portapapeles: {message}", + convertNamingStyle: "Cambiar estilo de nomenclatura", }, search: { find: "Buscar", @@ -6966,6 +6967,7 @@ export default withEnglishFallback({ customUiPrimary: "Color principal", customUiBorder: "Borde", customUiSidebar: "Barra lateral", + shortcutConvertNamingStyle: "Cambiar estilo de nomenclatura", }, driverStore: { jreDirRemoveFailed: "No se pudo eliminar el directorio JRE antiguo: {path} (error original: {error})", diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts index 2e2649d856..5df5ddcad7 100644 --- a/apps/desktop/src/i18n/locales/it.ts +++ b/apps/desktop/src/i18n/locales/it.ts @@ -1355,6 +1355,7 @@ export default withEnglishFallback({ cutSelection: "Taglia selezione", pasteFromClipboard: "Incolla", pasteClipboardReadFailed: "Impossibile leggere gli appunti: {message}", + convertNamingStyle: "Cambia stile di denominazione", }, search: { find: "Trova", @@ -6966,6 +6967,7 @@ export default withEnglishFallback({ customUiPrimary: "Colore principale", customUiBorder: "Bordo", customUiSidebar: "Barra laterale", + shortcutConvertNamingStyle: "Cambia stile di denominazione", }, driverStore: { jreDirRemoveFailed: "Impossibile rimuovere la vecchia directory JRE: {path} (errore originale: {error})", diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts index 575b53ffb7..87bb8ed85e 100644 --- a/apps/desktop/src/i18n/locales/ja.ts +++ b/apps/desktop/src/i18n/locales/ja.ts @@ -1375,6 +1375,7 @@ export default withEnglishFallback({ cutSelection: "選択内容を切り取る", pasteFromClipboard: "貼り付け", pasteClipboardReadFailed: "クリップボードの読み取りに失敗しました:{message}", + convertNamingStyle: "命名スタイルの切り替え", }, search: { find: "検索", @@ -7018,6 +7019,7 @@ export default withEnglishFallback({ customUiPrimary: "プライマリカラー", customUiBorder: "枠線", customUiSidebar: "サイドバー", + shortcutConvertNamingStyle: "命名スタイルの切り替え", }, driverStore: { jreDirRemoveFailed: "古い JRE ディレクトリを削除できませんでした: {path}(元のエラー: {error})", diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts index 7239893a02..e0a3153314 100644 --- a/apps/desktop/src/i18n/locales/ko.ts +++ b/apps/desktop/src/i18n/locales/ko.ts @@ -1266,6 +1266,7 @@ export default withEnglishFallback({ findReplace: "찾기/바꾸기", deleteEmptyLines: "빈 줄 삭제", selectAll: "모두 선택", + convertNamingStyle: "네이밍 스타일 전환", }, delimitedList: { title: "구분자 목록으로 변환", @@ -6673,6 +6674,7 @@ export default withEnglishFallback({ csvQuoteModeDescription: "CSV 내보내기 시 필드에 큰따옴표를 사용하는 방식을 선택합니다.", csvQuoteModeAll: "모든 필드", csvQuoteModeNecessary: "필수 필드만", + shortcutConvertNamingStyle: "네이밍 스타일 전환", }, driverStore: { jreDirRemoveFailed: "이전 JRE 디렉터리 제거 실패: {path} (원래 오류: {error})", diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts index 6c36d2eee8..ec3567a263 100644 --- a/apps/desktop/src/i18n/locales/pt-BR.ts +++ b/apps/desktop/src/i18n/locales/pt-BR.ts @@ -1356,6 +1356,7 @@ export default withEnglishFallback({ cutSelection: "Recortar seleção", pasteFromClipboard: "Colar", pasteClipboardReadFailed: "Falha ao ler a área de transferência: {message}", + convertNamingStyle: "Alternar estilo de nomenclatura", }, search: { find: "Localizar", @@ -6968,6 +6969,7 @@ export default withEnglishFallback({ customUiPrimary: "Cor primária", customUiBorder: "Borda", customUiSidebar: "Barra lateral", + shortcutConvertNamingStyle: "Alternar estilo de nomenclatura", }, driverStore: { jreDirRemoveFailed: "Não foi possível remover o diretório JRE antigo: {path} (erro original: {error})", diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts index 4ce8b9b72d..afd6b3fabe 100644 --- a/apps/desktop/src/i18n/locales/zh-CN.ts +++ b/apps/desktop/src/i18n/locales/zh-CN.ts @@ -1299,6 +1299,7 @@ export default withEnglishFallback({ sendToAi: "发送到 AI", uppercaseSelection: "转为大写", lowercaseSelection: "转为小写", + convertNamingStyle: "切换命名风格", delimitedList: "转换为带分隔符的列表", addNextSelectionOccurrence: "增加下一个选中词", selectAllSelectionOccurrences: "选中所有选中词", @@ -6907,6 +6908,7 @@ export default withEnglishFallback({ shortcutExtendSelection: "扩展选择", shortcutUppercaseSelection: "选中内容转为大写", shortcutLowercaseSelection: "选中内容转为小写", + shortcutConvertNamingStyle: "切换命名风格", shortcutExPasteSqlInCondition: "ExPaste:粘贴为 IN 条件", shortcutEditTableStructure: "编辑表结构", shortcutCopyCurrentRow: "复制当前数据行", diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts index c666d40a48..f115261c33 100644 --- a/apps/desktop/src/i18n/locales/zh-TW.ts +++ b/apps/desktop/src/i18n/locales/zh-TW.ts @@ -1355,6 +1355,7 @@ export default withEnglishFallback({ cutSelection: "剪下選取內容", pasteFromClipboard: "貼上", pasteClipboardReadFailed: "讀取剪貼簿失敗:{message}", + convertNamingStyle: "切換命名風格", }, search: { find: "尋找", @@ -6286,6 +6287,7 @@ export default withEnglishFallback({ customUiPrimary: "主色", customUiBorder: "邊框", customUiSidebar: "側邊欄", + shortcutConvertNamingStyle: "切換命名風格", }, driverStore: { jreDirRemoveFailed: "無法刪除舊的 JRE 目錄:{path}(原始錯誤:{error})", diff --git a/apps/desktop/src/lib/__tests__/editor/keyboardShortcuts.spec.ts b/apps/desktop/src/lib/__tests__/editor/keyboardShortcuts.spec.ts index 4cd87c57e9..e08227f390 100644 --- a/apps/desktop/src/lib/__tests__/editor/keyboardShortcuts.spec.ts +++ b/apps/desktop/src/lib/__tests__/editor/keyboardShortcuts.spec.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { eventToModifierOnlyShortcut, eventToShortcut, + isConvertNamingStyleShortcut, isEditTableStructureShortcut, isExecuteSqlInNewResultTabShortcut, isGoToColumnShortcut, @@ -49,6 +50,20 @@ describe("keyboard shortcut matching", () => { expect(eventToShortcut({ key, code, altKey: true, shiftKey: true }, "MacIntel")).toBe(expected); }); + it("matches the naming style shortcut by physical key and rejects extra modifiers", () => { + const macEvent = { key: "Ç", code: "KeyC", altKey: true, shiftKey: true }; + expect(isConvertNamingStyleShortcut(macEvent, undefined, "MacIntel")).toBe(true); + expect(isConvertNamingStyleShortcut({ key: "c", code: "KeyC", altKey: true, shiftKey: true }, undefined, "Win32")).toBe(true); + + // Extra Ctrl/Meta held must not fire the Shift+Alt+C default binding. + expect(isConvertNamingStyleShortcut({ ...macEvent, ctrlKey: true }, undefined, "MacIntel")).toBe(false); + expect(isConvertNamingStyleShortcut({ ...macEvent, metaKey: true }, undefined, "MacIntel")).toBe(false); + + // Custom settings are honored. + expect(isConvertNamingStyleShortcut({ key: "n", code: "KeyN", altKey: true, shiftKey: true }, { convertNamingStyle: "Shift+Alt+N" }, "Win32")).toBe(true); + expect(isConvertNamingStyleShortcut({ key: "c", code: "KeyC", altKey: true, shiftKey: true }, { convertNamingStyle: "Shift+Alt+N" }, "Win32")).toBe(false); + }); + it("keeps Control distinct from Command when recording macOS shortcuts", () => { const controlShortcut = eventToShortcut({ key: "b", ctrlKey: true }, "MacIntel"); diff --git a/apps/desktop/src/lib/editor/keyboardShortcuts.ts b/apps/desktop/src/lib/editor/keyboardShortcuts.ts index 8a59720fa4..ff4dc82650 100644 --- a/apps/desktop/src/lib/editor/keyboardShortcuts.ts +++ b/apps/desktop/src/lib/editor/keyboardShortcuts.ts @@ -145,6 +145,10 @@ export function isSendSelectionToAiShortcut(event: ShortcutLikeEvent, shortcuts? return matchesShortcut(event, actionShortcut("sendSelectionToAi", shortcuts)); } +export function isConvertNamingStyleShortcut(event: ShortcutLikeEvent, shortcuts?: Partial, platform = globalThis.navigator?.platform || ""): boolean { + return matchesShortcut(event, actionShortcut("convertNamingStyle", shortcuts, platform), platform); +} + export function isNewQueryShortcut(event: ShortcutLikeEvent, shortcuts?: Partial): boolean { return matchesShortcut(event, actionShortcut("newQuery", shortcuts)); } diff --git a/apps/desktop/src/lib/editor/shortcutRegistry.ts b/apps/desktop/src/lib/editor/shortcutRegistry.ts index 51f30ae1f8..2088757f42 100644 --- a/apps/desktop/src/lib/editor/shortcutRegistry.ts +++ b/apps/desktop/src/lib/editor/shortcutRegistry.ts @@ -28,6 +28,7 @@ export type ShortcutActionId = | "selectAllSelectionOccurrences" | "uppercaseSelection" | "lowercaseSelection" + | "convertNamingStyle" | "exPasteSqlInCondition" | "toggleFold" | "editTableStructure" @@ -292,6 +293,12 @@ export const SHORTCUT_DEFINITIONS: ShortcutDefinition[] = [ scope: "editor", defaultShortcut: "Shift+Alt+L", }, + { + id: "convertNamingStyle", + labelKey: "settings.shortcutConvertNamingStyle", + scope: "editor", + defaultShortcut: "Shift+Alt+C", + }, { id: "exPasteSqlInCondition", labelKey: "settings.shortcutExPasteSqlInCondition", diff --git a/apps/desktop/src/lib/naming/__tests__/namingStyleConverter.spec.ts b/apps/desktop/src/lib/naming/__tests__/namingStyleConverter.spec.ts new file mode 100644 index 0000000000..3b1723c923 --- /dev/null +++ b/apps/desktop/src/lib/naming/__tests__/namingStyleConverter.spec.ts @@ -0,0 +1,158 @@ +// @vitest-environment happy-dom + +import { describe, expect, it } from "vitest"; +import { convertToNextNamingStyle } from "../namingStyleConverter"; + +describe("namingStyleConverter", () => { + describe("convertToNextNamingStyle", () => { + it("cycles through all naming styles", () => { + // Start with camelCase + let result = convertToNextNamingStyle("userName"); + expect(result.text).toBe("UserName"); + expect(result.style).toBe("PascalCase"); + + // PascalCase → snake_case + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("user_name"); + expect(result.style).toBe("snake_case"); + + // snake_case → SCREAMING_SNAKE_CASE + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("USER_NAME"); + expect(result.style).toBe("SCREAMING_SNAKE_CASE"); + + // SCREAMING_SNAKE_CASE → kebab-case + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("user-name"); + expect(result.style).toBe("kebab-case"); + + // kebab-case → camelCase (cycle back) + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("userName"); + expect(result.style).toBe("camelCase"); + }); + + it("handles multi-word identifiers", () => { + let result = convertToNextNamingStyle("userNameList"); + expect(result.text).toBe("UserNameList"); + + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("user_name_list"); + + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("USER_NAME_LIST"); + + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("user-name-list"); + + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("userNameList"); + }); + + it("keeps a full five-state cycle for identifiers containing digits", () => { + let result = convertToNextNamingStyle("user2Name"); + expect(result.text).toBe("User2Name"); + expect(result.style).toBe("PascalCase"); + + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("user2_name"); + expect(result.style).toBe("snake_case"); + + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("USER2_NAME"); + expect(result.style).toBe("SCREAMING_SNAKE_CASE"); + + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("user2-name"); + expect(result.style).toBe("kebab-case"); + + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("user2Name"); + expect(result.style).toBe("camelCase"); + }); + + it("cycles common digit-bearing identifiers without collapsing", () => { + for (const identifier of ["ipv4Address", "field1Value", "sha256Hash"]) { + const seen = new Set(); + let current = identifier; + for (let hop = 0; hop < 5; hop += 1) { + current = convertToNextNamingStyle(current).text; + seen.add(current); + } + // Five hops must land back on the original text and pass through four + // distinct intermediate forms (the set holds all five results, the + // last of which is the original identifier again). + expect(current).toBe(identifier); + expect(seen.size).toBe(5); + } + }); + + it("preserves leading underscores through the cycle", () => { + let result = convertToNextNamingStyle("_privateField"); + expect(result.text).toBe("_PRIVATE_FIELD"); + expect(result.style).toBe("SCREAMING_SNAKE_CASE"); + + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("_private-field"); + expect(result.style).toBe("kebab-case"); + + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("_privateField"); + expect(result.style).toBe("camelCase"); + }); + + it("respects explicit currentStyle parameter", () => { + const result = convertToNextNamingStyle("test", "snake_case"); + expect(result.text).toBe("TEST"); + expect(result.style).toBe("SCREAMING_SNAKE_CASE"); + }); + + it("returns text unchanged for empty or non-identifier input", () => { + expect(convertToNextNamingStyle("").text).toBe(""); + expect(convertToNextNamingStyle(" ").text).toBe(" "); + expect(convertToNextNamingStyle("123").text).toBe("123"); + }); + + it("returns text unchanged for selections that are not a single identifier", () => { + expect(convertToNextNamingStyle("price - discount").text).toBe("price - discount"); + expect(convertToNextNamingStyle("-- fetch userName").text).toBe("-- fetch userName"); + expect(convertToNextNamingStyle("用户名").text).toBe("用户名"); + expect(convertToNextNamingStyle("userName\nlastName").text).toBe("userName\nlastName"); + }); + + it("preserves leading/trailing whitespace around the converted core", () => { + const result = convertToNextNamingStyle(" userName "); + expect(result.text).toBe(" UserName "); + expect(result.style).toBe("PascalCase"); + }); + + it("handles single-word identifiers (with ambiguity)", () => { + // Single lowercase words are ambiguous (could be camelCase, snake_case, or kebab-case) + // The cycle still works but may skip some styles + let result = convertToNextNamingStyle("user"); + expect(result.text).toBe("User"); // camelCase → PascalCase + expect(result.style).toBe("PascalCase"); + + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("user"); // PascalCase → snake_case + expect(result.style).toBe("snake_case"); + + // Note: "user" looks like camelCase to the detector, so it cycles back to PascalCase + result = convertToNextNamingStyle(result.text); + expect(result.text).toBe("User"); // detected as camelCase → PascalCase + expect(result.style).toBe("PascalCase"); + + // For proper cycling, use a multi-word identifier + let multiWord = convertToNextNamingStyle("userName"); + expect(multiWord.text).toBe("UserName"); + multiWord = convertToNextNamingStyle(multiWord.text); + expect(multiWord.text).toBe("user_name"); + multiWord = convertToNextNamingStyle(multiWord.text); + expect(multiWord.text).toBe("USER_NAME"); + multiWord = convertToNextNamingStyle(multiWord.text); + expect(multiWord.text).toBe("user-name"); + multiWord = convertToNextNamingStyle(multiWord.text); + expect(multiWord.text).toBe("userName"); // Full cycle complete + }); + }); +}); diff --git a/apps/desktop/src/lib/naming/__tests__/namingStyleDetector.spec.ts b/apps/desktop/src/lib/naming/__tests__/namingStyleDetector.spec.ts new file mode 100644 index 0000000000..00de5282c2 --- /dev/null +++ b/apps/desktop/src/lib/naming/__tests__/namingStyleDetector.spec.ts @@ -0,0 +1,52 @@ +// @vitest-environment happy-dom + +import { describe, expect, it } from "vitest"; +import { detectNamingStyle } from "../namingStyleDetector"; + +describe("namingStyleDetector", () => { + it("detects camelCase", () => { + expect(detectNamingStyle("userName")).toBe("camelCase"); + expect(detectNamingStyle("firstName")).toBe("camelCase"); + expect(detectNamingStyle("userNameList")).toBe("camelCase"); + }); + + it("detects PascalCase", () => { + expect(detectNamingStyle("UserName")).toBe("PascalCase"); + expect(detectNamingStyle("FirstName")).toBe("PascalCase"); + expect(detectNamingStyle("UserNameList")).toBe("PascalCase"); + }); + + it("detects snake_case", () => { + expect(detectNamingStyle("user_name")).toBe("snake_case"); + expect(detectNamingStyle("first_name")).toBe("snake_case"); + expect(detectNamingStyle("user_name_list")).toBe("snake_case"); + }); + + it("detects SCREAMING_SNAKE_CASE", () => { + expect(detectNamingStyle("USER_NAME")).toBe("SCREAMING_SNAKE_CASE"); + expect(detectNamingStyle("FIRST_NAME")).toBe("SCREAMING_SNAKE_CASE"); + expect(detectNamingStyle("USER_NAME_LIST")).toBe("SCREAMING_SNAKE_CASE"); + }); + + it("detects kebab-case", () => { + expect(detectNamingStyle("user-name")).toBe("kebab-case"); + expect(detectNamingStyle("first-name")).toBe("kebab-case"); + expect(detectNamingStyle("user-name-list")).toBe("kebab-case"); + }); + + it("returns null for empty or non-identifier text", () => { + expect(detectNamingStyle("")).toBeNull(); + expect(detectNamingStyle(" ")).toBeNull(); + expect(detectNamingStyle("123")).toBeNull(); + expect(detectNamingStyle("___")).toBeNull(); + }); + + it("handles mixed styles by priority", () => { + // Hyphen has highest priority + expect(detectNamingStyle("user-name_test")).toBe("kebab-case"); + // Underscore + uppercase = SCREAMING_SNAKE_CASE + expect(detectNamingStyle("USER_NAME")).toBe("SCREAMING_SNAKE_CASE"); + // Underscore + not all uppercase = snake_case + expect(detectNamingStyle("User_Name")).toBe("snake_case"); + }); +}); diff --git a/apps/desktop/src/lib/naming/__tests__/namingStyleTransformers.spec.ts b/apps/desktop/src/lib/naming/__tests__/namingStyleTransformers.spec.ts new file mode 100644 index 0000000000..9fdb64dd0a --- /dev/null +++ b/apps/desktop/src/lib/naming/__tests__/namingStyleTransformers.spec.ts @@ -0,0 +1,205 @@ +// @vitest-environment happy-dom + +import { describe, expect, it } from "vitest"; +import { convertToNamingStyle } from "../namingStyleTransformers"; + +describe("namingStyleTransformers", () => { + describe("convertToNamingStyle - camelCase", () => { + it("converts snake_case to camelCase", () => { + expect(convertToNamingStyle("user_name", "camelCase")).toBe("userName"); + expect(convertToNamingStyle("first_name_last", "camelCase")).toBe("firstNameLast"); + }); + + it("converts PascalCase to camelCase", () => { + expect(convertToNamingStyle("UserName", "camelCase")).toBe("userName"); + expect(convertToNamingStyle("FirstNameLast", "camelCase")).toBe("firstNameLast"); + }); + + it("converts kebab-case to camelCase", () => { + expect(convertToNamingStyle("user-name", "camelCase")).toBe("userName"); + expect(convertToNamingStyle("first-name-last", "camelCase")).toBe("firstNameLast"); + }); + + it("converts SCREAMING_SNAKE_CASE to camelCase", () => { + expect(convertToNamingStyle("USER_NAME", "camelCase")).toBe("userName"); + expect(convertToNamingStyle("FIRST_NAME_LAST", "camelCase")).toBe("firstNameLast"); + }); + }); + + describe("convertToNamingStyle - PascalCase", () => { + it("converts snake_case to PascalCase", () => { + expect(convertToNamingStyle("user_name", "PascalCase")).toBe("UserName"); + expect(convertToNamingStyle("first_name_last", "PascalCase")).toBe("FirstNameLast"); + }); + + it("converts camelCase to PascalCase", () => { + expect(convertToNamingStyle("userName", "PascalCase")).toBe("UserName"); + expect(convertToNamingStyle("firstNameLast", "PascalCase")).toBe("FirstNameLast"); + }); + + it("converts kebab-case to PascalCase", () => { + expect(convertToNamingStyle("user-name", "PascalCase")).toBe("UserName"); + expect(convertToNamingStyle("first-name-last", "PascalCase")).toBe("FirstNameLast"); + }); + }); + + describe("convertToNamingStyle - snake_case", () => { + it("converts camelCase to snake_case", () => { + expect(convertToNamingStyle("userName", "snake_case")).toBe("user_name"); + expect(convertToNamingStyle("firstNameLast", "snake_case")).toBe("first_name_last"); + }); + + it("converts PascalCase to snake_case", () => { + expect(convertToNamingStyle("UserName", "snake_case")).toBe("user_name"); + expect(convertToNamingStyle("FirstNameLast", "snake_case")).toBe("first_name_last"); + }); + + it("converts kebab-case to snake_case", () => { + expect(convertToNamingStyle("user-name", "snake_case")).toBe("user_name"); + expect(convertToNamingStyle("first-name-last", "snake_case")).toBe("first_name_last"); + }); + }); + + describe("convertToNamingStyle - SCREAMING_SNAKE_CASE", () => { + it("converts camelCase to SCREAMING_SNAKE_CASE", () => { + expect(convertToNamingStyle("userName", "SCREAMING_SNAKE_CASE")).toBe("USER_NAME"); + expect(convertToNamingStyle("firstNameLast", "SCREAMING_SNAKE_CASE")).toBe("FIRST_NAME_LAST"); + }); + + it("converts snake_case to SCREAMING_SNAKE_CASE", () => { + expect(convertToNamingStyle("user_name", "SCREAMING_SNAKE_CASE")).toBe("USER_NAME"); + expect(convertToNamingStyle("first_name_last", "SCREAMING_SNAKE_CASE")).toBe("FIRST_NAME_LAST"); + }); + + it("converts kebab-case to SCREAMING_SNAKE_CASE", () => { + expect(convertToNamingStyle("user-name", "SCREAMING_SNAKE_CASE")).toBe("USER_NAME"); + expect(convertToNamingStyle("first-name-last", "SCREAMING_SNAKE_CASE")).toBe("FIRST_NAME_LAST"); + }); + }); + + describe("convertToNamingStyle - kebab-case", () => { + it("converts camelCase to kebab-case", () => { + expect(convertToNamingStyle("userName", "kebab-case")).toBe("user-name"); + expect(convertToNamingStyle("firstNameLast", "kebab-case")).toBe("first-name-last"); + }); + + it("converts snake_case to kebab-case", () => { + expect(convertToNamingStyle("user_name", "kebab-case")).toBe("user-name"); + expect(convertToNamingStyle("first_name_last", "kebab-case")).toBe("first-name-last"); + }); + + it("converts PascalCase to kebab-case", () => { + expect(convertToNamingStyle("UserName", "kebab-case")).toBe("user-name"); + expect(convertToNamingStyle("FirstNameLast", "kebab-case")).toBe("first-name-last"); + }); + }); + + describe("digit boundaries", () => { + it("treats digit-to-letter transitions as word boundaries", () => { + expect(convertToNamingStyle("user2Name", "PascalCase")).toBe("User2Name"); + expect(convertToNamingStyle("user2Name", "snake_case")).toBe("user2_name"); + expect(convertToNamingStyle("user2Name", "SCREAMING_SNAKE_CASE")).toBe("USER2_NAME"); + expect(convertToNamingStyle("user2Name", "kebab-case")).toBe("user2-name"); + }); + + it("keeps digit runs attached to the preceding word", () => { + expect(convertToNamingStyle("ipv4Address", "snake_case")).toBe("ipv4_address"); + expect(convertToNamingStyle("sha256Hash", "snake_case")).toBe("sha256_hash"); + expect(convertToNamingStyle("field1Value", "PascalCase")).toBe("Field1Value"); + expect(convertToNamingStyle("field1Value", "snake_case")).toBe("field1_value"); + }); + + it("does not degrade mixed-case words through the cycle", () => { + // The pre-fix bug: user2Name → PascalCase produced "User2name" and the + // cycle collapsed into a two-state loop. + expect(convertToNamingStyle("user2Name", "PascalCase")).not.toBe("User2name"); + expect(convertToNamingStyle("User2Name", "snake_case")).toBe("user2_name"); + expect(convertToNamingStyle("user2_name", "SCREAMING_SNAKE_CASE")).toBe("USER2_NAME"); + expect(convertToNamingStyle("USER2_NAME", "kebab-case")).toBe("user2-name"); + expect(convertToNamingStyle("user2-name", "camelCase")).toBe("user2Name"); + }); + + it("handles identifiers that are all digits", () => { + expect(convertToNamingStyle("123", "camelCase")).toBe("123"); + expect(convertToNamingStyle("123", "PascalCase")).toBe("123"); + }); + }); + + describe("case preservation within words", () => { + it("keeps mixed-case word bodies intact for camel/Pascal targets", () => { + expect(convertToNamingStyle("user_name", "camelCase")).toBe("userName"); + expect(convertToNamingStyle("IP_address", "camelCase")).toBe("ipAddress"); + }); + + it("lowercases tails only for all-uppercase words", () => { + // SCREAMING words must fold (USER_NAME → userName), acronyms keep the + // already-approved flattening behavior (HTTPServer → HttpServer). + expect(convertToNamingStyle("USER_NAME", "camelCase")).toBe("userName"); + expect(convertToNamingStyle("HTTPServer", "PascalCase")).toBe("HttpServer"); + }); + }); + + describe("leading and trailing separators", () => { + it("preserves leading underscores", () => { + expect(convertToNamingStyle("_privateField", "SCREAMING_SNAKE_CASE")).toBe("_PRIVATE_FIELD"); + expect(convertToNamingStyle("_privateField", "snake_case")).toBe("_private_field"); + expect(convertToNamingStyle("_privateField", "kebab-case")).toBe("_private-field"); + expect(convertToNamingStyle("_privateField", "PascalCase")).toBe("_PrivateField"); + }); + + it("preserves repeated leading/trailing separator runs", () => { + expect(convertToNamingStyle("__CONSTANT_NAME__", "camelCase")).toBe("__constantName__"); + expect(convertToNamingStyle("__CONSTANT_NAME__", "kebab-case")).toBe("__constant-name__"); + }); + + it("preserves leading dollar signs", () => { + expect(convertToNamingStyle("$scopeValue", "PascalCase")).toBe("$ScopeValue"); + }); + }); + + describe("non-identifier input is left untouched", () => { + it("returns original text when content is not a single identifier", () => { + expect(convertToNamingStyle("price - discount", "camelCase")).toBe("price - discount"); + expect(convertToNamingStyle("-- fetch userName", "camelCase")).toBe("-- fetch userName"); + expect(convertToNamingStyle("a + b", "snake_case")).toBe("a + b"); + }); + + it("returns original text for CJK and Cyrillic content", () => { + expect(convertToNamingStyle("用户名", "camelCase")).toBe("用户名"); + expect(convertToNamingStyle("приветМир", "camelCase")).toBe("приветМир"); + }); + + it("returns original text for multi-line content", () => { + expect(convertToNamingStyle("userName\nlastName", "SCREAMING_SNAKE_CASE")).toBe("userName\nlastName"); + }); + + it("returns original text for empty, whitespace, or separator-only input", () => { + expect(convertToNamingStyle("", "camelCase")).toBe(""); + expect(convertToNamingStyle(" ", "camelCase")).toBe(" "); + expect(convertToNamingStyle("___", "camelCase")).toBe("___"); + }); + }); + + describe("whitespace preservation", () => { + it("keeps leading and trailing whitespace around the converted core", () => { + expect(convertToNamingStyle(" userName ", "PascalCase")).toBe(" UserName "); + expect(convertToNamingStyle("\tuser_name\n", "camelCase")).toBe("\tuserName\n"); + }); + }); + + describe("edge cases", () => { + it("handles single words", () => { + expect(convertToNamingStyle("user", "camelCase")).toBe("user"); + expect(convertToNamingStyle("user", "PascalCase")).toBe("User"); + expect(convertToNamingStyle("user", "snake_case")).toBe("user"); + expect(convertToNamingStyle("USER", "kebab-case")).toBe("user"); + }); + + it("handles complex camelCase boundaries", () => { + expect(convertToNamingStyle("userIDList", "snake_case")).toBe("user_id_list"); + expect(convertToNamingStyle("XMLParser", "kebab-case")).toBe("xml-parser"); + expect(convertToNamingStyle("parseHTTPResponse", "PascalCase")).toBe("ParseHttpResponse"); + expect(convertToNamingStyle("parseHTTPResponse", "snake_case")).toBe("parse_http_response"); + }); + }); +}); diff --git a/apps/desktop/src/lib/naming/namingStyleConverter.ts b/apps/desktop/src/lib/naming/namingStyleConverter.ts new file mode 100644 index 0000000000..bff7a8e247 --- /dev/null +++ b/apps/desktop/src/lib/naming/namingStyleConverter.ts @@ -0,0 +1,35 @@ +import { detectNamingStyle, type NamingStyle } from "./namingStyleDetector"; +import { convertToNamingStyle, SINGLE_IDENTIFIER_PATTERN } from "./namingStyleTransformers"; + +export interface NamingStyleConversionResult { + text: string; + style: NamingStyle; +} + +const STYLE_CYCLE: NamingStyle[] = ["camelCase", "PascalCase", "snake_case", "SCREAMING_SNAKE_CASE", "kebab-case"]; + +function getNextStyle(currentStyle: NamingStyle): NamingStyle { + const currentIndex = STYLE_CYCLE.indexOf(currentStyle); + const nextIndex = (currentIndex + 1) % STYLE_CYCLE.length; + return STYLE_CYCLE[nextIndex]; +} + +/** + * Convert to the next naming style in the cycle: + * camelCase → PascalCase → snake_case → SCREAMING_SNAKE_CASE → kebab-case. + * + * Returns the original text unchanged (no-op) when the trimmed content is not + * a single identifier — e.g. selections containing whitespace, operators, + * comments, CJK/Cyrillic letters, or line breaks. Whitespace surrounding the + * identifier is preserved. + */ +export function convertToNextNamingStyle(text: string, currentStyle?: NamingStyle): NamingStyleConversionResult { + const core = text.trim(); + const detectedStyle = currentStyle ?? detectNamingStyle(core); + if (!detectedStyle || !SINGLE_IDENTIFIER_PATTERN.test(core)) { + return { text, style: detectedStyle ?? "camelCase" }; + } + + const nextStyle = getNextStyle(detectedStyle); + return { text: convertToNamingStyle(text, nextStyle), style: nextStyle }; +} diff --git a/apps/desktop/src/lib/naming/namingStyleDetector.ts b/apps/desktop/src/lib/naming/namingStyleDetector.ts new file mode 100644 index 0000000000..7db7893bae --- /dev/null +++ b/apps/desktop/src/lib/naming/namingStyleDetector.ts @@ -0,0 +1,14 @@ +export type NamingStyle = "camelCase" | "PascalCase" | "snake_case" | "SCREAMING_SNAKE_CASE" | "kebab-case"; + +export function detectNamingStyle(text: string): NamingStyle | null { + const trimmed = text.trim(); + if (!trimmed || !/[a-zA-Z]/.test(trimmed)) return null; + + // Priority order matters + if (trimmed.includes("-")) return "kebab-case"; + if (trimmed.includes("_")) { + return trimmed === trimmed.toUpperCase() ? "SCREAMING_SNAKE_CASE" : "snake_case"; + } + if (/^[A-Z]/.test(trimmed)) return "PascalCase"; + return "camelCase"; +} diff --git a/apps/desktop/src/lib/naming/namingStyleTransformers.ts b/apps/desktop/src/lib/naming/namingStyleTransformers.ts new file mode 100644 index 0000000000..7756d12a41 --- /dev/null +++ b/apps/desktop/src/lib/naming/namingStyleTransformers.ts @@ -0,0 +1,97 @@ +import type { NamingStyle } from "./namingStyleDetector"; + +/** + * A single identifier: letters, digits, and identifier separator characters. + * Selections that do not match (spaces, operators, comments, CJK/Cyrillic + * text, multi-line content) are left untouched instead of being rewritten. + */ +export const SINGLE_IDENTIFIER_PATTERN = /^[A-Za-z0-9_$-]+$/; + +const LEADING_SEPARATOR_PATTERN = /^[_$-]+/; +const TRAILING_SEPARATOR_PATTERN = /[_$-]+$/; +const SEPARATOR_RUN_PATTERN = /[_$-]+/; +// Word boundaries inside an identifier segment: lower→Upper (userName), +// UPPER→Upper+lower (HTTPServer), and digit→letter (user2Name / sha256Hash). +// Letter→digit is deliberately NOT a boundary so digit runs stay attached to +// the preceding word (ipv4, sha256, field1). +const WORD_BOUNDARY_PATTERN = /(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?<=[0-9])(?=[A-Za-z])/; + +interface IdentifierParts { + leading: string; + words: string[]; + trailing: string; +} + +function splitIntoWords(core: string): IdentifierParts { + const leadingMatch = LEADING_SEPARATOR_PATTERN.exec(core); + const leading = leadingMatch ? leadingMatch[0] : ""; + const trailingMatch = TRAILING_SEPARATOR_PATTERN.exec(core); + const trailing = trailingMatch ? trailingMatch[0] : ""; + const inner = core.slice(leading.length, core.length - trailing.length); + const words = inner + .split(SEPARATOR_RUN_PATTERN) + .flatMap((segment) => segment.split(WORD_BOUNDARY_PATTERN)) + .filter((word) => word.length > 0); + return { leading, words, trailing }; +} + +/** + * Capitalize a word for camelCase/PascalCase output. Only all-uppercase words + * (SCREAMING_SNAKE chunks and acronyms) fold their tail to lowercase; + * mixed-case words keep their body so `user2Name` survives as `User2Name` + * instead of degrading to `User2name`. + */ +function capitalizeWord(word: string): string { + if (word.length <= 1) return word.toUpperCase(); + const isAllUppercase = word === word.toUpperCase(); + return word.charAt(0).toUpperCase() + (isAllUppercase ? word.slice(1).toLowerCase() : word.slice(1)); +} + +/** + * Convert text to specified naming style. + * + * Leading/trailing whitespace and separator runs (`_`, `$`, `-`) are preserved + * verbatim; only the identifier core is rewritten. Text that is not a single + * identifier (after trimming whitespace) is returned unchanged. + */ +export function convertToNamingStyle(text: string, targetStyle: NamingStyle): string { + if (!text) return text; + + const core = text.trim(); + if (!core || !SINGLE_IDENTIFIER_PATTERN.test(core)) return text; + + const whitespaceStart = text.length - text.trimStart().length; + const leadingWhitespace = text.slice(0, whitespaceStart); + const trailingWhitespace = text.slice(whitespaceStart + core.length); + + const { leading, words, trailing } = splitIntoWords(core); + if (words.length === 0) return text; + + let converted: string; + switch (targetStyle) { + case "camelCase": + converted = words.map((word, index) => (index === 0 ? word.toLowerCase() : capitalizeWord(word))).join(""); + break; + + case "PascalCase": + converted = words.map(capitalizeWord).join(""); + break; + + case "snake_case": + converted = words.map((word) => word.toLowerCase()).join("_"); + break; + + case "SCREAMING_SNAKE_CASE": + converted = words.map((word) => word.toUpperCase()).join("_"); + break; + + case "kebab-case": + converted = words.map((word) => word.toLowerCase()).join("-"); + break; + + default: + return text; + } + + return leadingWhitespace + leading + converted + trailing + trailingWhitespace; +} diff --git a/docs/content/docs/keyboard-shortcuts.cn.mdx b/docs/content/docs/keyboard-shortcuts.cn.mdx index 0bf08294d9..e24f516a4d 100644 --- a/docs/content/docs/keyboard-shortcuts.cn.mdx +++ b/docs/content/docs/keyboard-shortcuts.cn.mdx @@ -25,6 +25,7 @@ DBX 的快捷键来自同一份可配置 action registry。**设置 → 快捷 | `Alt+↑` / `Alt+↓` | 上下移动当前行 | | `Shift+Alt+↑` / `Shift+Alt+↓` | 向上/下复制当前行 | | `Shift+Alt+U` / `Shift+Alt+L` | 选中内容转大写/小写 | +| `Shift+Alt+C` | 切换选中内容的命名风格(camelCase → PascalCase → snake_case → SCREAMING_SNAKE_CASE → kebab-case) | | `Mod+.` | 折叠或展开代码块 | | `Mod+Shift+A` | 把选中内容发送给 AI | diff --git a/docs/content/docs/keyboard-shortcuts.mdx b/docs/content/docs/keyboard-shortcuts.mdx index c8ffc3c01f..e7de511b42 100644 --- a/docs/content/docs/keyboard-shortcuts.mdx +++ b/docs/content/docs/keyboard-shortcuts.mdx @@ -25,6 +25,7 @@ DBX shortcuts come from one configurable action registry. **Settings → Shortcu | `Alt+↑` / `Alt+↓` | Move current line up/down | | `Shift+Alt+↑` / `Shift+Alt+↓` | Copy current line up/down | | `Shift+Alt+U` / `Shift+Alt+L` | Convert selection to uppercase/lowercase | +| `Shift+Alt+C` | Toggle selection naming style (camelCase → PascalCase → snake_case → SCREAMING_SNAKE_CASE → kebab-case) | | `Mod+.` | Toggle code folding | | `Mod+Shift+A` | Send selection to AI |