From 077ded2ccefbfdbac5b0fc360d593da468d52d33 Mon Sep 17 00:00:00 2001 From: Chenlei Hu Date: Mon, 6 Jan 2025 19:46:20 -0500 Subject: [PATCH] [Refactor] Simplify keybindingStore with _.groupBy (#2180) --- src/stores/keybindingStore.ts | 16 +++------------- tests-ui/tests/store/keybindingStore.test.ts | 12 ++++++++++++ 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/src/stores/keybindingStore.ts b/src/stores/keybindingStore.ts index ec9da6a0f..bcdc2cf2b 100644 --- a/src/stores/keybindingStore.ts +++ b/src/stores/keybindingStore.ts @@ -1,3 +1,4 @@ +import _ from 'lodash' import { defineStore } from 'pinia' import { Ref, computed, ref, toRaw } from 'vue' @@ -145,20 +146,9 @@ export const useKeybindingStore = defineStore('keybinding', () => { return keybindingByKeyCombo.value[combo.serialize()] } - function createKeybindingsByCommandId(keybindings: KeybindingImpl[]) { - const result: Record = {} - for (const keybinding of keybindings) { - if (!(keybinding.commandId in result)) { - result[keybinding.commandId] = [] - } - result[keybinding.commandId].push(keybinding) - } - return result - } - const keybindingsByCommandId = computed>( () => { - return createKeybindingsByCommandId(keybindings.value) + return _.groupBy(keybindings.value, 'commandId') } ) @@ -169,7 +159,7 @@ export const useKeybindingStore = defineStore('keybinding', () => { const defaultKeybindingsByCommandId = computed< Record >(() => { - return createKeybindingsByCommandId(Object.values(defaultKeybindings.value)) + return _.groupBy(Object.values(defaultKeybindings.value), 'commandId') }) function getKeybindingByCommandId(commandId: string) { diff --git a/tests-ui/tests/store/keybindingStore.test.ts b/tests-ui/tests/store/keybindingStore.test.ts index 66cb90408..dfcd3789a 100644 --- a/tests-ui/tests/store/keybindingStore.test.ts +++ b/tests-ui/tests/store/keybindingStore.test.ts @@ -33,6 +33,18 @@ describe('useKeybindingStore', () => { expect(store.getKeybinding(keybinding.combo)).toEqual(keybinding) }) + it('should get keybindings by command id', () => { + const store = useKeybindingStore() + const keybinding = new KeybindingImpl({ + commandId: 'test.command', + combo: { key: 'C', ctrl: true } + }) + store.addDefaultKeybinding(keybinding) + expect(store.getKeybindingsByCommandId('test.command')).toEqual([ + keybinding + ]) + }) + it('should override default keybindings with user keybindings', () => { const store = useKeybindingStore() const defaultKeybinding = new KeybindingImpl({