diff --git a/packages/keybindings/src/keybindingStore.ts b/packages/keybindings/src/keybindingStore.ts index b314b7f0a54..cfbec4d1014 100644 --- a/packages/keybindings/src/keybindingStore.ts +++ b/packages/keybindings/src/keybindingStore.ts @@ -9,12 +9,70 @@ import type { KeybindingPreset } from './types' type KeybindingMap = Partial> +interface UserChoices { + user: KeybindingMap + unset: KeybindingMap + pendingUnset: KeybindingImpl[] +} + +export interface KeybindingConflict { + existing: KeybindingImpl + incoming: KeybindingImpl +} + +export type KeymapChange = + | { ok: true; changed: boolean } + | { ok: false; reason: 'conflict'; conflict: KeybindingConflict } + +interface KeymapWriteOptions { + replaceConflicts?: boolean +} + +interface SavedChoices { + newBindings: KeybindingImpl[] + unsetBindings: KeybindingImpl[] +} + +const EMPTY_USER_CHOICES: UserChoices = { + user: {}, + unset: {}, + pendingUnset: [] +} + function keybindingValues(keybindings: KeybindingMap): KeybindingImpl[] { return Object.values(keybindings).filter( (keybinding): keybinding is KeybindingImpl => keybinding !== undefined ) } +function withoutCombo(keybindings: KeybindingMap, serializedCombo: string) { + const { [serializedCombo]: _removed, ...remaining } = keybindings + return remaining +} + +function refuseConflict( + existing: KeybindingImpl, + incoming: KeybindingImpl +): KeymapChange { + return { ok: false, reason: 'conflict', conflict: { existing, incoming } } +} + +export function findSavedChoiceConflicts( + bindings: KeybindingImpl[] +): KeybindingConflict[] { + const claimed = new Map() + const conflicts: KeybindingConflict[] = [] + for (const incoming of bindings) { + const serializedCombo = incoming.combo.serialize() + const existing = claimed.get(serializedCombo) + if (existing && !existing.equals(incoming)) { + conflicts.push({ existing, incoming }) + } + claimed.set(serializedCombo, incoming) + } + return conflicts +} + export const useKeybindingStore = defineStore('keybinding', () => { const defaultKeybindings = shallowRef({}) const userKeybindings = shallowRef({}) @@ -83,12 +141,12 @@ export const useKeybindingStore = defineStore('keybinding', () => { ] } - const keybindingByKeyCombo = computed(() => { + function effectiveKeymap(choices: UserChoices): KeybindingMap { const result: KeybindingMap = { ...defaultKeybindings.value } - for (const keybinding of keybindingValues(userUnsetKeybindings.value)) { + for (const keybinding of keybindingValues(choices.unset)) { const serializedCombo = keybinding.combo.serialize() if (result[serializedCombo]?.equals(keybinding)) { delete result[serializedCombo] @@ -97,9 +155,122 @@ export const useKeybindingStore = defineStore('keybinding', () => { return { ...result, - ...userKeybindings.value + ...choices.user } - }) + } + + function currentChoices(): UserChoices { + return { + user: userKeybindings.value, + unset: userUnsetKeybindings.value, + pendingUnset: pendingUnsetKeybindings.value + } + } + + function commitChoices(choices: UserChoices) { + userKeybindings.value = choices.user + userUnsetKeybindings.value = choices.unset + pendingUnsetKeybindings.value = choices.pendingUnset + } + + function withUnsetChoice( + choices: UserChoices, + keybinding: KeybindingImpl + ): UserChoices { + const serializedCombo = keybinding.combo.serialize() + const registeredDefault = defaultKeybindings.value[serializedCombo] + if (registeredDefault) { + return registeredDefault.equals(keybinding) + ? { + ...choices, + unset: { ...choices.unset, [serializedCombo]: keybinding } + } + : choices + } + return choices.pendingUnset.some((unset) => unset.equals(keybinding)) + ? choices + : { ...choices, pendingUnset: [...choices.pendingUnset, keybinding] } + } + + function withUserBinding( + choices: UserChoices, + keybinding: KeybindingImpl + ): UserChoices { + const serializedCombo = keybinding.combo.serialize() + const defaultKeybinding = defaultKeybindings.value[serializedCombo] + const userUnsetKeybinding = choices.unset[serializedCombo] + + if ( + keybinding.equals(defaultKeybinding) && + keybinding.equals(userUnsetKeybinding) + ) { + return { + ...choices, + user: withoutCombo(choices.user, serializedCombo), + unset: withoutCombo(choices.unset, serializedCombo) + } + } + + return { + ...choices, + unset: + defaultKeybinding && !defaultKeybinding.equals(userUnsetKeybinding) + ? { ...choices.unset, [serializedCombo]: defaultKeybinding } + : choices.unset, + user: { ...choices.user, [serializedCombo]: keybinding } + } + } + + function withoutBinding( + choices: UserChoices, + keybinding: KeybindingImpl + ): UserChoices { + const serializedCombo = keybinding.combo.serialize() + if (!(serializedCombo in effectiveKeymap(choices))) { + console.warn( + `Trying to unset non-exist keybinding: ${JSON.stringify(keybinding)}` + ) + return choices + } + + if (choices.user[serializedCombo]?.equals(keybinding)) { + return { ...choices, user: withoutCombo(choices.user, serializedCombo) } + } + + if (defaultKeybindings.value[serializedCombo]?.equals(keybinding)) { + return { + ...choices, + unset: { ...choices.unset, [serializedCombo]: keybinding } + } + } + + console.warn(`Unset unknown keybinding: ${JSON.stringify(keybinding)}`) + return choices + } + + function withoutBindings( + choices: UserChoices, + keybindings: KeybindingImpl[] + ): UserChoices { + return keybindings.reduce(withoutBinding, choices) + } + + function writeUserBinding( + base: UserChoices, + keybinding: KeybindingImpl, + { replaceConflicts = false }: KeymapWriteOptions + ): KeymapChange { + const existing = effectiveKeymap(base)[keybinding.combo.serialize()] + if (existing && !existing.equals(keybinding) && !replaceConflicts) { + return refuseConflict(existing, keybinding) + } + commitChoices(withUserBinding(base, keybinding)) + return { ok: true, changed: true } + } + + const keybindingByKeyCombo = computed(() => + effectiveKeymap(currentChoices()) + ) const keybindings = computed(() => keybindingValues(keybindingByKeyCombo.value) @@ -156,136 +327,114 @@ export const useKeybindingStore = defineStore('keybinding', () => { addKeybinding(userUnsetKeybindings, keybinding, { existOk: true }) } - function addUserUnsetKeybinding(keybinding: KeybindingImpl) { - const registeredDefault = - defaultKeybindings.value[keybinding.combo.serialize()] - if (registeredDefault) { - if (registeredDefault.equals(keybinding)) { - addKeybinding(userUnsetKeybindings, keybinding, { existOk: true }) - } - return - } - if (pendingUnsetKeybindings.value.some((unset) => unset.equals(keybinding))) - return - pendingUnsetKeybindings.value = [ - ...pendingUnsetKeybindings.value, - keybinding - ] + function addUserKeybinding( + keybinding: KeybindingImpl, + options: KeymapWriteOptions = {} + ): KeymapChange { + return writeUserBinding(currentChoices(), keybinding, options) } - function addUserKeybinding(keybinding: KeybindingImpl) { - const serializedCombo = keybinding.combo.serialize() - const defaultKeybinding = defaultKeybindings.value[serializedCombo] - const userUnsetKeybinding = userUnsetKeybindings.value[serializedCombo] + function userChoicesFromSaved({ + newBindings, + unsetBindings + }: SavedChoices): UserChoices { + return newBindings.reduce( + withUserBinding, + unsetBindings.reduce(withUnsetChoice, EMPTY_USER_CHOICES) + ) + } - if ( - keybinding.equals(defaultKeybinding) && - keybinding.equals(userUnsetKeybinding) - ) { - const updated = { ...userUnsetKeybindings.value } - delete updated[keybinding.combo.serialize()] - userUnsetKeybindings.value = updated - return - } + function applySavedChoices({ + newBindings, + unsetBindings + }: SavedChoices): KeymapChange { + const conflict = findSavedChoiceConflicts(newBindings).at(0) + if (conflict) return refuseConflict(conflict.existing, conflict.incoming) - if (defaultKeybinding && !defaultKeybinding.equals(userUnsetKeybinding)) { - unsetKeybinding(defaultKeybinding) - } + commitChoices(userChoicesFromSaved({ newBindings, unsetBindings })) + return { ok: true, changed: true } + } - addKeybinding(userKeybindings, keybinding, { existOk: true }) + function restoreSavedChoices(saved: SavedChoices): KeybindingConflict[] { + commitChoices(userChoicesFromSaved(saved)) + return findSavedChoiceConflicts(saved.newBindings) } function unsetKeybinding(keybinding: KeybindingImpl) { - const serializedCombo = keybinding.combo.serialize() - if (!(serializedCombo in keybindingByKeyCombo.value)) { - console.warn( - `Trying to unset non-exist keybinding: ${JSON.stringify(keybinding)}` - ) - return - } - - if (userKeybindings.value[serializedCombo]?.equals(keybinding)) { - const updated = { ...userKeybindings.value } - delete updated[serializedCombo] - userKeybindings.value = updated - return - } - - if (defaultKeybindings.value[serializedCombo]?.equals(keybinding)) { - addKeybinding(userUnsetKeybindings, keybinding, { existOk: false }) - return - } - - console.warn(`Unset unknown keybinding: ${JSON.stringify(keybinding)}`) + commitChoices(withoutBinding(currentChoices(), keybinding)) } - function updateKeybindingOnCommand(keybinding: KeybindingImpl): boolean { + function updateKeybindingOnCommand( + keybinding: KeybindingImpl, + options: KeymapWriteOptions = {} + ): KeymapChange { const currentKeybinding = getKeybindingByCommandId(keybinding.commandId) if (currentKeybinding?.equals(keybinding)) { - return false - } - if (currentKeybinding) { - unsetKeybinding(currentKeybinding) + return { ok: true, changed: false } } - addUserKeybinding(keybinding) - return true + const base = currentKeybinding + ? withoutBinding(currentChoices(), currentKeybinding) + : currentChoices() + return writeUserBinding(base, keybinding, options) } function resetAllKeybindings() { - userKeybindings.value = {} - userUnsetKeybindings.value = {} - pendingUnsetKeybindings.value = [] + commitChoices(EMPTY_USER_CHOICES) } function removeAllKeybindingsForCommand(commandId: string): boolean { const currentBindings = getKeybindingsByCommandId(commandId) if (currentBindings.length === 0) return false - for (const binding of currentBindings) { - unsetKeybinding(binding) - } + commitChoices(withoutBindings(currentChoices(), currentBindings)) return true } function updateSpecificKeybinding( oldBinding: KeybindingImpl, - newBinding: KeybindingImpl - ) { - unsetKeybinding(oldBinding) - addUserKeybinding(newBinding) + newBinding: KeybindingImpl, + options: KeymapWriteOptions = {} + ): KeymapChange { + return writeUserBinding( + withoutBinding(currentChoices(), oldBinding), + newBinding, + options + ) } - function resetKeybindingForCommand(commandId: string): boolean { + function resetKeybindingForCommand(commandId: string): KeymapChange { const currentBindings = getKeybindingsByCommandId(commandId) const defaultBindings = defaultKeybindingsByCommandId.value[commandId] ?? [] if (defaultBindings.length === 0) { - if (currentBindings.length > 0) { - for (const binding of currentBindings) { - unsetKeybinding(binding) - } - return true - } - return false + if (currentBindings.length === 0) return { ok: true, changed: false } + commitChoices(withoutBindings(currentChoices(), currentBindings)) + return { ok: true, changed: true } } if (!isCommandKeybindingModified(commandId)) { - return false + return { ok: true, changed: false } } - for (const binding of currentBindings) { - unsetKeybinding(binding) + const withoutCurrent = withoutBindings(currentChoices(), currentBindings) + const candidate: UserChoices = { + ...withoutCurrent, + unset: defaultBindings.reduce( + (unset, defaultBinding) => + withoutCombo(unset, defaultBinding.combo.serialize()), + withoutCurrent.unset + ) } - const updatedUnset = { ...userUnsetKeybindings.value } + const keymap = effectiveKeymap(candidate) for (const defaultBinding of defaultBindings) { - const serializedCombo = defaultBinding.combo.serialize() - if (updatedUnset[serializedCombo]?.equals(defaultBinding)) { - delete updatedUnset[serializedCombo] + const holder = keymap[defaultBinding.combo.serialize()] + if (holder && !holder.equals(defaultBinding)) { + return refuseConflict(holder, defaultBinding) } } - userUnsetKeybindings.value = updatedUnset - return true + commitChoices(candidate) + return { ok: true, changed: true } } const modifiedCommandIds = computed>(() => { @@ -336,7 +485,8 @@ export const useKeybindingStore = defineStore('keybinding', () => { getKeybindingByCommandId, addDefaultKeybinding, addUserKeybinding, - addUserUnsetKeybinding, + applySavedChoices, + restoreSavedChoices, unsetKeybinding, updateKeybindingOnCommand, resetAllKeybindings, diff --git a/packages/keybindings/src/types.ts b/packages/keybindings/src/types.ts index 470d0cefe6a..778fa5fa062 100644 --- a/packages/keybindings/src/types.ts +++ b/packages/keybindings/src/types.ts @@ -8,7 +8,7 @@ const zKeyCombo = z.object({ meta: z.boolean().optional() }) -const zKeybinding = z.object({ +export const zKeybinding = z.object({ commandId: z.string(), combo: zKeyCombo, targetElementId: z.string().optional() diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 9c5aec2ac6e..52efdc24748 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -107,6 +107,7 @@ "resetAllKeybindingsTitle": "Reset all keybindings?", "resetAllKeybindingsMessage": "All keybindings will be reset to their default values. This cannot be undone.", "allKeybindingsReset": "All keybindings reset to default", + "keybindingResetConflict": "Can't reset: {key} is assigned to {command}. Assign {key} to this command to overwrite it, or remove it from {command} first.", "removeAllKeybindingsTitle": "Remove all keybindings?", "removeAllKeybindingsMessage": "All keybindings for this command will be removed", "removeAll": "Remove all", @@ -358,6 +359,7 @@ "browserReservedKeybindingTooltip": "This shortcut conflicts with browser-reserved shortcuts", "keybindingAlreadyExists": "Keybinding already exists on", "keybindingPresets": { + "presetConflict": "Preset \"{name}\" wasn't applied because it assigns {key} to more than one command. Your keybindings are unchanged.", "importPreset": "Import preset", "importKeybindingPreset": "Import keybinding preset", "exportPreset": "Export preset", diff --git a/src/platform/keybindings/components/EditKeybindingFooter.test.ts b/src/platform/keybindings/components/EditKeybindingFooter.test.ts new file mode 100644 index 00000000000..a0e144b0dcd --- /dev/null +++ b/src/platform/keybindings/components/EditKeybindingFooter.test.ts @@ -0,0 +1,71 @@ +import userEvent from '@testing-library/user-event' +import { render, screen } from '@testing-library/vue' +import { describe, expect, it, vi } from 'vitest' +import { reactive } from 'vue' + +import { KeyComboImpl } from '@comfyorg/keybindings/keyCombo' +import { KeybindingImpl } from '@comfyorg/keybindings/keybinding' +import { useKeybindingStore } from '@comfyorg/keybindings/keybindingStore' +import { useSettingStore } from '@/platform/settings/settingStore' +import { useDialogStore } from '@/stores/dialogStore' +import { testI18n } from '@/utils/__tests__/testI18n' + +import EditKeybindingFooter from './EditKeybindingFooter.vue' +import { EDIT_KEYBINDING_DIALOG_KEY } from './editKeybindingDialogState' +import type { EditKeybindingDialogState } from './editKeybindingDialogState' + +const ctrlK = { key: 'k', ctrl: true } + +function renderFooter(existingKeybindingOnCombo: KeybindingImpl | null) { + const dialogState = reactive({ + commandId: 'test.incoming', + newCombo: new KeyComboImpl(ctrlK), + currentCombo: null, + mode: 'add', + existingBinding: null + }) + return render(EditKeybindingFooter, { + props: { dialogState, existingKeybindingOnCombo }, + global: { plugins: [testI18n] } + }) +} + +describe('EditKeybindingFooter', () => { + it('replaces the holder and persists when Overwrite is confirmed', async () => { + const settingStore = useSettingStore() + vi.mocked(settingStore.setMany).mockResolvedValue(undefined) + const store = useKeybindingStore() + const holder = new KeybindingImpl({ + commandId: 'test.holder', + combo: ctrlK + }) + store.addDefaultKeybinding(holder) + renderFooter(holder) + + await userEvent.click(screen.getByRole('button', { name: 'Overwrite' })) + + expect(store.getKeybinding(holder.combo)?.commandId).toBe('test.incoming') + expect(store.getKeybindingsByCommandId('test.holder')).toEqual([]) + expect(settingStore.setMany).toHaveBeenCalledOnce() + expect(useDialogStore().closeDialog).toHaveBeenCalledWith({ + key: EDIT_KEYBINDING_DIALOG_KEY + }) + }) + + it('stays open and persists nothing when the combo became occupied after the dialog offered Save', async () => { + const settingStore = useSettingStore() + const store = useKeybindingStore() + const holder = new KeybindingImpl({ + commandId: 'test.holder', + combo: ctrlK + }) + store.addDefaultKeybinding(holder) + renderFooter(null) + + await userEvent.click(screen.getByRole('button', { name: 'Save' })) + + expect(store.getKeybinding(holder.combo)).toEqual(holder) + expect(settingStore.setMany).not.toHaveBeenCalled() + expect(useDialogStore().closeDialog).not.toHaveBeenCalled() + }) +}) diff --git a/src/platform/keybindings/components/EditKeybindingFooter.vue b/src/platform/keybindings/components/EditKeybindingFooter.vue index a8f515c5639..c29c849f091 100644 --- a/src/platform/keybindings/components/EditKeybindingFooter.vue +++ b/src/platform/keybindings/components/EditKeybindingFooter.vue @@ -57,20 +57,25 @@ async function handleSave() { const commandId = dialogState.commandId if (!combo || !commandId) return + const saved = saveBinding(new KeybindingImpl({ commandId, combo })) + if (!saved.ok) return + dialogStore.closeDialog({ key: EDIT_KEYBINDING_DIALOG_KEY }) + await keybindingService.persistUserKeybindings() +} +function saveBinding(binding: KeybindingImpl) { + const options = { replaceConflicts: Boolean(existingKeybindingOnCombo) } if (dialogState.mode === 'add') { - keybindingStore.addUserKeybinding(new KeybindingImpl({ commandId, combo })) - } else if (dialogState.existingBinding) { - keybindingStore.updateSpecificKeybinding( + return keybindingStore.addUserKeybinding(binding, options) + } + if (dialogState.existingBinding) { + return keybindingStore.updateSpecificKeybinding( dialogState.existingBinding, - new KeybindingImpl({ commandId, combo }) - ) - } else { - keybindingStore.updateKeybindingOnCommand( - new KeybindingImpl({ commandId, combo }) + binding, + options ) } - await keybindingService.persistUserKeybindings() + return keybindingStore.updateKeybindingOnCommand(binding, options) } diff --git a/src/platform/keybindings/components/KeybindingPanel.test.ts b/src/platform/keybindings/components/KeybindingPanel.test.ts index 6fe480931c0..c9136de3caf 100644 --- a/src/platform/keybindings/components/KeybindingPanel.test.ts +++ b/src/platform/keybindings/components/KeybindingPanel.test.ts @@ -6,6 +6,7 @@ import { describe, expect, it, onTestFinished, vi } from 'vitest' import { nextTick } from 'vue' import GlobalDialog from '@/components/dialog/GlobalDialog.vue' +import { useToast } from '@/components/ui/toast/toastStore' import { testI18n } from '@/utils/__tests__/testI18n' import { KeybindingImpl } from '@comfyorg/keybindings/keybinding' import { useKeybindingStore } from '@comfyorg/keybindings/keybindingStore' @@ -340,6 +341,36 @@ describe('KeybindingPanel', () => { expect(screen.queryByRole('menu')).not.toBeInTheDocument() }) + it('names the holder and persists nothing when a reset is refused', async () => { + const user = userEvent.setup() + registerCommand('command-default', 'Default command', ['R']) + registerCommand('command-holder', 'Holder command') + useKeybindingStore().addUserKeybinding( + new KeybindingImpl({ + commandId: 'command-holder', + combo: { key: 'R', ctrl: true } + }), + { replaceConflicts: true } + ) + renderPanel() + + const row = screen.getByRole('row', { name: /Default command/ }) + await user.click(within(row).getByRole('button', { name: 'Reset' })) + + await waitFor(() => + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'error', + title: expect.stringContaining('Holder command') + }) + ]) + ) + expect(useSettingStore().setMany).not.toHaveBeenCalled() + expect( + useKeybindingStore().getKeybindingsByCommandId('command-holder') + ).toHaveLength(1) + }) + it('closes the reset-all confirmation when saving fails', async () => { const user = userEvent.setup() const saveError = new Error('offline') diff --git a/src/platform/keybindings/components/KeybindingPanel.vue b/src/platform/keybindings/components/KeybindingPanel.vue index 4cfe542c067..61fe4dc64f1 100644 --- a/src/platform/keybindings/components/KeybindingPanel.vue +++ b/src/platform/keybindings/components/KeybindingPanel.vue @@ -227,7 +227,13 @@ const menuEntries = computed(() => [ } ]) -// Keybinding table logic +function commandLabel(commandId: string) { + return t( + `commands.${normalizeI18nKey(commandId)}.label`, + commandStore.getCommand(commandId)?.label ?? commandId + ) +} + const commandsData = computed(() => { return Object.values(commandStore.commands).map((command) => { const keybindings = keybindingStore.getKeybindingsByCommandId(command.id) @@ -236,10 +242,7 @@ const commandsData = computed(() => { id: command.id, isModified: keybindingStore.isCommandKeybindingModified(command.id), keybindings, - label: t( - `commands.${normalizeI18nKey(command.id)}.label`, - command.label ?? command.id - ), + label: commandLabel(command.id), rowId: `keybinding-row-${command.id}`, source: command.source } @@ -437,7 +440,17 @@ function changeKeybinding(command: KeybindingCommand) { } async function resetKeybinding(command: KeybindingCommand) { - if (keybindingStore.resetKeybindingForCommand(command.id)) { + const reset = keybindingStore.resetKeybindingForCommand(command.id) + if (!reset.ok) { + toast.error( + t('g.keybindingResetConflict', { + key: reset.conflict.incoming.combo.toString(), + command: commandLabel(reset.conflict.existing.commandId) + }) + ) + return + } + if (reset.changed) { expandedCommandIds.value.delete(command.id) await keybindingService.persistUserKeybindings() } else { diff --git a/src/platform/keybindings/keybindingService.registerUserKeybindings.test.ts b/src/platform/keybindings/keybindingService.registerUserKeybindings.test.ts index d90e9c547f3..1d199ed108a 100644 --- a/src/platform/keybindings/keybindingService.registerUserKeybindings.test.ts +++ b/src/platform/keybindings/keybindingService.registerUserKeybindings.test.ts @@ -2,8 +2,14 @@ import { useSettingStore } from '@/platform/settings/settingStore' import { beforeEach, describe, expect, it, vi } from 'vitest' import { KeybindingImpl } from '@comfyorg/keybindings/keybinding' +import { reportError } from '@comfyorg/telemetry/reportError' import { useKeybindingService } from '@/platform/keybindings/keybindingService' import { useKeybindingStore } from '@comfyorg/keybindings/keybindingStore' +import type { Keybinding } from '@comfyorg/keybindings/types' + +vi.mock(import('@comfyorg/telemetry/reportError'), () => ({ + reportError: vi.fn() +})) describe('keybindingService - registerUserKeybindings', () => { beforeEach(() => { @@ -95,6 +101,132 @@ describe('keybindingService - registerUserKeybindings', () => { ) }) + it('reports saved bindings that claim one combo and keeps the last one active', () => { + const keybindingStore = useKeybindingStore() + const combo = { key: 'k', ctrl: true, alt: false, shift: false } + useSettingStore().settingValues['Comfy.Keybinding.NewBindings'] = [ + { commandId: 'Comfy.Test.First', combo }, + { commandId: 'Comfy.Test.Second', combo } + ] + + useKeybindingService().registerUserKeybindings() + + expect( + keybindingStore.getUserKeybindingValues().map((b) => b.commandId) + ).toEqual(['Comfy.Test.Second']) + expect(reportError).toHaveBeenCalledExactlyOnceWith( + expect.any(Error), + expect.objectContaining({ + errorType: 'failure_restoring_user_keybindings', + tags: { outcome: 'degraded' } + }) + ) + }) + + it('keeps other saved shortcuts when an edit persists after a clashing restore', async () => { + const settingStore = useSettingStore() + vi.mocked(settingStore.setMany).mockResolvedValue(undefined) + const clashing = { key: 'k', ctrl: true, alt: false, shift: false } + const unrelated = { key: 'l', ctrl: true, alt: false, shift: false } + settingStore.settingValues['Comfy.Keybinding.NewBindings'] = [ + { commandId: 'Comfy.Test.First', combo: clashing }, + { commandId: 'Comfy.Test.Second', combo: clashing }, + { commandId: 'Comfy.Test.Unrelated', combo: unrelated } + ] + + const keybindingService = useKeybindingService() + keybindingService.registerUserKeybindings() + useKeybindingStore().addUserKeybinding( + new KeybindingImpl({ + commandId: 'Comfy.Test.Edited', + combo: { key: 'm', ctrl: true, alt: false, shift: false } + }) + ) + await keybindingService.persistUserKeybindings() + + expect(settingStore.setMany).toHaveBeenCalledWith( + expect.objectContaining({ + 'Comfy.Keybinding.NewBindings': [ + expect.objectContaining({ commandId: 'Comfy.Test.Second' }), + expect.objectContaining({ commandId: 'Comfy.Test.Unrelated' }), + expect.objectContaining({ commandId: 'Comfy.Test.Edited' }) + ] + }) + ) + }) + + describe('with malformed saved entries', () => { + const ctrlA = { key: 'a', ctrl: true, alt: false, shift: false } + const ctrlB = { key: 'b', ctrl: true, alt: false, shift: false } + + function settingsFromDisk(entries: unknown[]): Keybinding[] { + return JSON.parse(JSON.stringify(entries)) + } + + it.for([ + { name: 'no combo', malformed: { commandId: 'Comfy.Test.Bad' } }, + { + name: 'no key', + malformed: { commandId: 'Comfy.Test.Bad', combo: { ctrl: true } } + }, + { name: 'no command', malformed: { combo: ctrlA } } + ])( + 'keeps every other saved shortcut through a save when a binding has $name', + async ({ malformed }) => { + const settingStore = useSettingStore() + vi.mocked(settingStore.setMany).mockResolvedValue(undefined) + settingStore.settingValues['Comfy.Keybinding.NewBindings'] = + settingsFromDisk([ + { commandId: 'Comfy.Test.Before', combo: ctrlA }, + malformed, + { commandId: 'Comfy.Test.After', combo: ctrlB } + ]) + + const keybindingService = useKeybindingService() + keybindingService.registerUserKeybindings() + await keybindingService.persistUserKeybindings() + + expect(settingStore.setMany).toHaveBeenCalledWith( + expect.objectContaining({ + 'Comfy.Keybinding.NewBindings': [ + expect.objectContaining({ commandId: 'Comfy.Test.Before' }), + expect.objectContaining({ commandId: 'Comfy.Test.After' }) + ] + }) + ) + expect(reportError).toHaveBeenCalledExactlyOnceWith( + expect.any(Error), + expect.objectContaining({ + errorType: 'failure_restoring_user_keybindings', + tags: { outcome: 'degraded' }, + context: { invalidCount: 1 } + }) + ) + } + ) + + it('keeps saved shortcuts and valid unsets when an unset entry is malformed', () => { + const keybindingStore = useKeybindingStore() + const settingStore = useSettingStore() + const unset = { commandId: 'Comfy.Test.Unset', combo: ctrlA } + keybindingStore.addDefaultKeybinding(new KeybindingImpl(unset)) + settingStore.settingValues['Comfy.Keybinding.UnsetBindings'] = + settingsFromDisk([{ commandId: 'Comfy.Test.Bad' }, unset]) + settingStore.settingValues['Comfy.Keybinding.NewBindings'] = [ + { commandId: 'Comfy.Test.Saved', combo: ctrlB } + ] + + useKeybindingService().registerUserKeybindings() + + expect( + keybindingStore.getKeybindingsByCommandId('Comfy.Test.Unset') + ).toEqual([]) + expect( + keybindingStore.getKeybindingsByCommandId('Comfy.Test.Saved') + ).toHaveLength(1) + }) + }) + it('does not mark the default preset modified for an unset still waiting for its binding', () => { useSettingStore().settingValues['Comfy.Keybinding.UnsetBindings'] = [ { diff --git a/src/platform/keybindings/keybindingService.ts b/src/platform/keybindings/keybindingService.ts index 0c3b8942f41..bc4dbfd9556 100644 --- a/src/platform/keybindings/keybindingService.ts +++ b/src/platform/keybindings/keybindingService.ts @@ -1,3 +1,5 @@ +import { reportError } from '@comfyorg/telemetry/reportError' + import { isCloud } from '@/platform/distribution/types' import { useSettingStore } from '@/platform/settings/settingStore' import { useCommandStore } from '@/platform/keybindings/commandStore' @@ -9,6 +11,32 @@ import { consultEscapeOverride } from './escapeOverride' import { KeyComboImpl } from '@comfyorg/keybindings/keyCombo' import { KeybindingImpl } from '@comfyorg/keybindings/keybinding' import { useKeybindingStore } from '@comfyorg/keybindings/keybindingStore' +import { zKeybinding } from '@comfyorg/keybindings/types' + +function readSavedBindings(saved: unknown[]) { + const valid = saved.flatMap((entry) => { + const parsed = zKeybinding.safeParse(entry) + return parsed.success ? [parsed.data] : [] + }) + return { + bindings: valid + .filter((binding) => !isExcludedFromDistribution(binding)) + .map((binding) => new KeybindingImpl(binding)), + invalidCount: saved.length - valid.length + } +} + +function reportDegradedRestore( + message: string, + context: Record +) { + reportError(new Error(message), { + errorType: 'failure_restoring_user_keybindings', + surface: 'platform', + tags: { outcome: 'degraded' }, + context + }) +} function isExcludedFromDistribution(keybinding: { commandId: string }) { return ( @@ -146,15 +174,31 @@ export function useKeybindingService() { } function registerUserKeybindings() { - const unsetBindings = settingStore.get('Comfy.Keybinding.UnsetBindings') - for (const keybinding of unsetBindings) { - if (isExcludedFromDistribution(keybinding)) continue - keybindingStore.addUserUnsetKeybinding(new KeybindingImpl(keybinding)) + const unset = readSavedBindings( + settingStore.get('Comfy.Keybinding.UnsetBindings') + ) + const added = readSavedBindings( + settingStore.get('Comfy.Keybinding.NewBindings') + ) + const conflicts = keybindingStore.restoreSavedChoices({ + unsetBindings: unset.bindings, + newBindings: added.bindings + }) + + const invalidCount = unset.invalidCount + added.invalidCount + if (invalidCount > 0) { + reportDegradedRestore('Saved keybindings contain malformed entries', { + invalidCount + }) } - const newBindings = settingStore.get('Comfy.Keybinding.NewBindings') - for (const keybinding of newBindings) { - if (isExcludedFromDistribution(keybinding)) continue - keybindingStore.addUserKeybinding(new KeybindingImpl(keybinding)) + const conflict = conflicts.at(0) + if (conflict) { + reportDegradedRestore('Saved keybindings claim the same key combo', { + combo: conflict.incoming.combo.serialize(), + existingCommandId: conflict.existing.commandId, + incomingCommandId: conflict.incoming.commandId, + conflictCount: conflicts.length + }) } } diff --git a/src/platform/keybindings/keybindingStore.test.ts b/src/platform/keybindings/keybindingStore.test.ts index 69a713bedce..2dc58a43b95 100644 --- a/src/platform/keybindings/keybindingStore.test.ts +++ b/src/platform/keybindings/keybindingStore.test.ts @@ -42,22 +42,205 @@ describe('useKeybindingStore', () => { ]) }) - it('should override default keybindings with user keybindings', () => { + it('should replace a default keybinding when replacement is explicit', () => { const store = useKeybindingStore() const defaultKeybinding = new KeybindingImpl({ commandId: 'test.command1', combo: { key: 'C', ctrl: true } }) + const unrelatedKeybinding = new KeybindingImpl({ + commandId: 'test.unrelated', + combo: { key: 'U', ctrl: true } + }) const userKeybinding = new KeybindingImpl({ commandId: 'test.command2', combo: { key: 'C', ctrl: true } }) store.addDefaultKeybinding(defaultKeybinding) - store.addUserKeybinding(userKeybinding) + store.addDefaultKeybinding(unrelatedKeybinding) + const result = store.addUserKeybinding(userKeybinding, { + replaceConflicts: true + }) - expect(store.keybindings).toHaveLength(1) + expect(result).toEqual({ ok: true, changed: true }) expect(store.getKeybinding(userKeybinding.combo)).toEqual(userKeybinding) + expect(store.getKeybindingsByCommandId('test.command1')).toEqual([]) + expect(store.getKeybinding(unrelatedKeybinding.combo)).toEqual( + unrelatedKeybinding + ) + }) + + describe('writes that claim an occupied combo without explicit replacement', () => { + function holderOnCtrlC() { + return new KeybindingImpl({ + commandId: 'test.holder', + combo: { key: 'C', ctrl: true } + }) + } + function incomingOnCtrlC() { + return new KeybindingImpl({ + commandId: 'test.incoming', + combo: { key: 'C', ctrl: true } + }) + } + + it.for([ + { + name: 'a default holds the combo', + hold: (holder: KeybindingImpl) => + useKeybindingStore().addDefaultKeybinding(holder) + }, + { + name: 'a user binding holds the combo', + hold: (holder: KeybindingImpl) => + useKeybindingStore().addUserKeybinding(holder) + } + ])('refuses an added binding when $name', ({ hold }) => { + const store = useKeybindingStore() + const holder = holderOnCtrlC() + const incoming = incomingOnCtrlC() + hold(holder) + + const result = store.addUserKeybinding(incoming) + + expect(result).toEqual({ + ok: false, + reason: 'conflict', + conflict: { existing: holder, incoming } + }) + expect(store.getKeybinding(holder.combo)).toEqual(holder) + expect(store.getKeybindingsByCommandId('test.incoming')).toEqual([]) + }) + + it('keeps the old binding when moving a specific binding is refused', () => { + const store = useKeybindingStore() + const holder = holderOnCtrlC() + const original = new KeybindingImpl({ + commandId: 'test.incoming', + combo: { key: 'D', ctrl: true } + }) + store.addDefaultKeybinding(holder) + store.addDefaultKeybinding(original) + + const result = store.updateSpecificKeybinding(original, incomingOnCtrlC()) + + expect(result.ok).toBe(false) + expect(store.getKeybinding(original.combo)).toEqual(original) + expect(store.getKeybinding(holder.combo)).toEqual(holder) + expect(store.getUserUnsetKeybindingValues()).toEqual([]) + }) + + it('keeps the current binding when changing a command binding is refused', () => { + const store = useKeybindingStore() + const holder = holderOnCtrlC() + const original = new KeybindingImpl({ + commandId: 'test.incoming', + combo: { key: 'D', ctrl: true } + }) + store.addDefaultKeybinding(holder) + store.addUserKeybinding(original) + + const result = store.updateKeybindingOnCommand(incomingOnCtrlC()) + + expect(result.ok).toBe(false) + expect(store.getKeybinding(original.combo)).toEqual(original) + expect(store.getKeybinding(holder.combo)).toEqual(holder) + }) + }) + + describe('applySavedChoices', () => { + it('leaves the live keymap unchanged when a later entry conflicts', () => { + const store = useKeybindingStore() + const live = new KeybindingImpl({ + commandId: 'test.live', + combo: { key: 'L', ctrl: true } + }) + store.addUserKeybinding(live) + + const result = store.applySavedChoices({ + unsetBindings: [], + newBindings: [ + new KeybindingImpl({ + commandId: 'test.first', + combo: { key: 'F', ctrl: true } + }), + new KeybindingImpl({ + commandId: 'test.second', + combo: { key: 'F', ctrl: true } + }) + ] + }) + + expect(result.ok).toBe(false) + expect(store.getUserKeybindingValues()).toEqual([live]) + expect(store.getKeybindingsByCommandId('test.first')).toEqual([]) + }) + + it('lets a saved choice keep a combo a default also claims', () => { + const store = useKeybindingStore() + const proposed = new KeybindingImpl({ + commandId: 'test.default', + combo: { key: 'K', ctrl: true } + }) + const saved = new KeybindingImpl({ + commandId: 'test.saved', + combo: { key: 'K', ctrl: true } + }) + store.addDefaultKeybinding(proposed) + + const result = store.applySavedChoices({ + unsetBindings: [], + newBindings: [saved] + }) + + expect(result).toEqual({ ok: true, changed: true }) + expect(store.getKeybinding(saved.combo)).toEqual(saved) + }) + + it('replaces every earlier user choice', () => { + const store = useKeybindingStore() + store.addUserKeybinding( + new KeybindingImpl({ + commandId: 'test.previous', + combo: { key: 'P', ctrl: true } + }) + ) + const saved = new KeybindingImpl({ + commandId: 'test.saved', + combo: { key: 'S', ctrl: true } + }) + + store.applySavedChoices({ unsetBindings: [], newBindings: [saved] }) + + expect(store.getUserKeybindingValues()).toEqual([saved]) + }) + }) + + describe('resetKeybindingForCommand with an occupied default combo', () => { + it('refuses and keeps both bindings when another command holds the combo', () => { + const store = useKeybindingStore() + const defaultBinding = new KeybindingImpl({ + commandId: 'test.default', + combo: { key: 'R', ctrl: true } + }) + const overwriting = new KeybindingImpl({ + commandId: 'test.overwriting', + combo: { key: 'R', ctrl: true } + }) + store.addDefaultKeybinding(defaultBinding) + store.addUserKeybinding(overwriting, { replaceConflicts: true }) + + const result = store.resetKeybindingForCommand('test.default') + + expect(result).toEqual({ + ok: false, + reason: 'conflict', + conflict: { existing: overwriting, incoming: defaultBinding } + }) + expect(store.getKeybinding(overwriting.combo)).toEqual(overwriting) + expect(store.getUserUnsetKeybindingValues()).toEqual([defaultBinding]) + }) }) it('Should allow binding to unsetted default keybindings', () => { @@ -118,7 +301,7 @@ describe('useKeybindingStore', () => { expect(() => store.addDefaultKeybinding(keybinding)).toThrow() }) - it('should allow adding duplicate user keybindings', () => { + it('should replace a user keybinding when replacement is explicit', () => { const store = useKeybindingStore() const keybinding1 = new KeybindingImpl({ commandId: 'test.command1', @@ -130,12 +313,42 @@ describe('useKeybindingStore', () => { }) store.addUserKeybinding(keybinding1) - store.addUserKeybinding(keybinding2) + store.addUserKeybinding(keybinding2, { replaceConflicts: true }) expect(store.keybindings).toHaveLength(1) expect(store.getKeybinding(keybinding2.combo)).toEqual(keybinding2) }) + it('takes a combo back from its holder when explicitly moving a command onto its own unset default', () => { + const store = useKeybindingStore() + const combo = { key: 'S', ctrl: true } + const defaultBinding = new KeybindingImpl({ + commandId: 'test.save', + combo + }) + const holder = new KeybindingImpl({ commandId: 'test.rename', combo }) + const customBinding = new KeybindingImpl({ + commandId: 'test.save', + combo: { key: 'X', ctrl: true, shift: true } + }) + store.addDefaultKeybinding(defaultBinding) + store.addUserKeybinding(holder, { replaceConflicts: true }) + store.addUserKeybinding(customBinding) + + const moved = store.updateSpecificKeybinding( + customBinding, + defaultBinding, + { replaceConflicts: true } + ) + + expect(moved).toEqual({ ok: true, changed: true }) + expect(store.getKeybinding(defaultBinding.combo)).toEqual(defaultBinding) + expect(store.getKeybindingsByCommandId('test.rename')).toEqual([]) + expect(store.getKeybindingsByCommandId('test.save')).toEqual([ + defaultBinding + ]) + }) + it('should not throw an error when unsetting non-existent keybindings', () => { const store = useKeybindingStore() const keybinding = new KeybindingImpl({ @@ -265,7 +478,7 @@ describe('useKeybindingStore', () => { combo: { key: 'A', ctrl: true } }) - store.updateKeybindingOnCommand(newKeybinding) + store.updateKeybindingOnCommand(newKeybinding, { replaceConflicts: true }) expect(store.keybindings).toHaveLength(1) expect(store.getKeybinding(newKeybinding.combo)).toMatchObject({ @@ -274,13 +487,13 @@ describe('useKeybindingStore', () => { expect(store.getKeybindingsByCommandId('command1')).toHaveLength(0) }) - it('should return false when no default or current keybinding exists during reset', () => { + it('should report no change when no default or current keybinding exists during reset', () => { const store = useKeybindingStore() const result = store.resetKeybindingForCommand('nonexistent.command') - expect(result).toBe(false) + expect(result).toEqual({ ok: true, changed: false }) }) - it('should return false when current keybinding equals default keybinding', () => { + it('should report no change when current keybinding equals default keybinding', () => { const store = useKeybindingStore() const defaultKeybinding = new KeybindingImpl({ commandId: 'test.command', @@ -290,7 +503,7 @@ describe('useKeybindingStore', () => { store.addDefaultKeybinding(defaultKeybinding) const result = store.resetKeybindingForCommand('test.command') - expect(result).toBe(false) + expect(result).toEqual({ ok: true, changed: false }) expect(store.keybindings).toHaveLength(1) expect(store.getKeybindingByCommandId('test.command')).toEqual( defaultKeybinding @@ -309,7 +522,7 @@ describe('useKeybindingStore', () => { const result = store.resetKeybindingForCommand('test.command') - expect(result).toBe(true) + expect(result).toEqual({ ok: true, changed: true }) expect(store.keybindings).toHaveLength(0) }) @@ -336,7 +549,7 @@ describe('useKeybindingStore', () => { const result = store.resetKeybindingForCommand('test.command') - expect(result).toBe(true) + expect(result).toEqual({ ok: true, changed: true }) expect(store.keybindings).toHaveLength(1) expect(store.getKeybindingByCommandId('test.command')).toEqual( defaultKeybinding @@ -362,7 +575,7 @@ describe('useKeybindingStore', () => { const result = store.resetKeybindingForCommand('test.command') - expect(result).toBe(true) + expect(result).toEqual({ ok: true, changed: true }) expect(store.keybindings).toHaveLength(1) expect(store.getKeybindingByCommandId('test.command')).toEqual( defaultKeybinding @@ -395,7 +608,7 @@ describe('useKeybindingStore', () => { const result = store.resetKeybindingForCommand('test.command') - expect(result).toBe(true) + expect(result).toEqual({ ok: true, changed: true }) expect(store.keybindings).toHaveLength(1) expect(store.getKeybindingByCommandId('test.command')).toEqual( defaultKeybinding @@ -518,7 +731,7 @@ describe('useKeybindingStore', () => { const result = store.resetKeybindingForCommand('test.command') - expect(result).toBe(true) + expect(result).toEqual({ ok: true, changed: true }) expect(store.getKeybindingsByCommandId('test.command')).toHaveLength(2) }) @@ -539,7 +752,7 @@ describe('useKeybindingStore', () => { const result = store.resetKeybindingForCommand('test.command') - expect(result).toBe(true) + expect(result).toEqual({ ok: true, changed: true }) expect(store.getKeybindingsByCommandId('test.command')).toHaveLength(0) }) }) diff --git a/src/platform/keybindings/presetService.test.ts b/src/platform/keybindings/presetService.test.ts index 3cd7956ad78..1056609ccdc 100644 --- a/src/platform/keybindings/presetService.test.ts +++ b/src/platform/keybindings/presetService.test.ts @@ -1,3 +1,4 @@ +import { useToast } from '@/components/ui/toast/toastStore' import { useSettingStore } from '@/platform/settings/settingStore' import { useDialogService } from '@/services/dialogService' import { useDialogStore } from '@/stores/dialogStore' @@ -255,6 +256,31 @@ describe('useKeybindingPresetService', () => { ) }) + it('stores nothing when the imported preset conflicts with itself', async () => { + const conflicting: KeybindingPreset = { + name: 'broken', + newBindings: [ + { commandId: 'first.cmd', combo: { key: 'A', ctrl: true } }, + { commandId: 'second.cmd', combo: { key: 'A', ctrl: true } } + ], + unsetBindings: [] + } + mockUploadFile.mockResolvedValue( + new File([JSON.stringify(conflicting)], 'broken.json', { + type: 'application/json' + }) + ) + + const service = await getPresetService() + await service.importPreset() + + expect(api.storeUserData).not.toHaveBeenCalled() + expect(store.currentPresetName).toBe('default') + expect(useToast().toasts).toEqual([ + expect.objectContaining({ kind: 'error' }) + ]) + }) + it('saves preset to storage and switches to it', async () => { const validPreset: KeybindingPreset = { name: 'imported', @@ -442,6 +468,30 @@ describe('useKeybindingPresetService', () => { ).toEqual(['test.selectAll']) }) + it('leaves the keymap and preset name unchanged when a later entry conflicts', async () => { + const live = new KeybindingImpl({ + commandId: 'live.cmd', + combo: { key: 'Z', ctrl: true } + }) + store.addUserKeybinding(live) + const preset: KeybindingPreset = { + name: 'broken', + newBindings: [ + { commandId: 'first.cmd', combo: { key: 'A', ctrl: true } }, + { commandId: 'second.cmd', combo: { key: 'A', ctrl: true } } + ], + unsetBindings: [] + } + + const service = await getPresetService() + const applied = service.applyPreset(preset) + + expect(applied.ok).toBe(false) + expect(store.getUserKeybindingValues()).toEqual([live]) + expect(store.currentPresetName).toBe('default') + expect(store.savedPresetData).toBeNull() + }) + it('keeps an unset for a binding that registers after the preset is applied', async () => { const combo = { key: 'd', ctrl: true } const preset: KeybindingPreset = { @@ -463,6 +513,30 @@ describe('useKeybindingPresetService', () => { }) describe('switchPreset', () => { + it('persists nothing when the target preset conflicts with itself', async () => { + const conflicting: KeybindingPreset = { + name: 'broken', + newBindings: [ + { commandId: 'first.cmd', combo: { key: 'A', ctrl: true } }, + { commandId: 'second.cmd', combo: { key: 'A', ctrl: true } } + ], + unsetBindings: [] + } + vi.mocked(api.getUserData).mockResolvedValueOnce( + new Response(JSON.stringify(conflicting), { status: 200 }) + ) + + const service = await getPresetService() + await service.switchPreset('broken') + + expect(store.currentPresetName).toBe('default') + expect(mockPersistUserKeybindings).not.toHaveBeenCalled() + expect(mockSettingSet).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([ + expect.objectContaining({ kind: 'error' }) + ]) + }) + it('discards unsaved changes when dialog returns false', async () => { store.addUserKeybinding( new KeybindingImpl({ diff --git a/src/platform/keybindings/presetService.ts b/src/platform/keybindings/presetService.ts index 880967d6282..a49e95c975f 100644 --- a/src/platform/keybindings/presetService.ts +++ b/src/platform/keybindings/presetService.ts @@ -15,7 +15,14 @@ import { useDialogStore } from '@/stores/dialogStore' import { KeybindingImpl } from '@comfyorg/keybindings/keybinding' import { useKeybindingService } from './keybindingService' -import { useKeybindingStore } from '@comfyorg/keybindings/keybindingStore' +import { + findSavedChoiceConflicts, + useKeybindingStore +} from '@comfyorg/keybindings/keybindingStore' +import type { + KeybindingConflict, + KeymapChange +} from '@comfyorg/keybindings/keybindingStore' import type { KeybindingPreset } from '@comfyorg/keybindings/types' import { zKeybindingPreset } from '@comfyorg/keybindings/types' @@ -111,22 +118,28 @@ export function useKeybindingPresetService() { return { ...result.data, name } } - function applyPreset(preset: KeybindingPreset) { - keybindingStore.resetAllKeybindings() - for (const binding of preset.unsetBindings) { - keybindingStore.addUserUnsetKeybinding(new KeybindingImpl(binding)) - } - for (const binding of preset.newBindings) { - keybindingStore.addUserKeybinding(new KeybindingImpl(binding)) - } - // Snapshot savedPresetData from the store's actual state after applying, - // because addUserKeybinding may auto-unset conflicting defaults beyond - // what the raw preset specifies. + function applyPreset(preset: KeybindingPreset): KeymapChange { + const applied = keybindingStore.applySavedChoices({ + newBindings: preset.newBindings.map((b) => new KeybindingImpl(b)), + unsetBindings: preset.unsetBindings.map((b) => new KeybindingImpl(b)) + }) + if (!applied.ok) return applied + keybindingStore.savedPresetData = buildPresetFromStore( preset.name, keybindingStore ) keybindingStore.currentPresetName = preset.name + return applied + } + + function notifyPresetConflict(name: string, conflict: KeybindingConflict) { + toast.error( + t('g.keybindingPresets.presetConflict', { + name, + key: conflict.incoming.combo.toString() + }) + ) } async function savePreset(name: string) { @@ -198,14 +211,20 @@ export function useKeybindingPresetService() { } const preset = result.data - // Save the imported preset file to storage + const conflict = findSavedChoiceConflicts( + preset.newBindings.map((b) => new KeybindingImpl(b)) + ).at(0) + if (conflict) { + notifyPresetConflict(preset.name, conflict) + return + } + await api.storeUserData( presetFilePath(preset.name), JSON.stringify(preset), { overwrite: true, stringify: false } ) - // Switch to the imported preset (handles dirty check) await switchPreset(preset.name) toast.success(t('g.keybindingPresets.presetImported'), { duration: 3000 }) @@ -260,7 +279,11 @@ export function useKeybindingPresetService() { } const preset = await loadPreset(targetName) - applyPreset(preset) + const applied = applyPreset(preset) + if (!applied.ok) { + notifyPresetConflict(targetName, applied.conflict) + return + } await keybindingService.persistUserKeybindings() await settingStore.set('Comfy.Keybinding.CurrentPreset', targetName) }