Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
334 changes: 242 additions & 92 deletions packages/keybindings/src/keybindingStore.ts

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/keybindings/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 2 additions & 0 deletions src/locales/en/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
@@ -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<EditKeybindingDialogState>({
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()
})
})
23 changes: 14 additions & 9 deletions src/platform/keybindings/components/EditKeybindingFooter.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
</script>
31 changes: 31 additions & 0 deletions src/platform/keybindings/components/KeybindingPanel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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')
Expand Down
25 changes: 19 additions & 6 deletions src/platform/keybindings/components/KeybindingPanel.vue
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,13 @@ const menuEntries = computed<MenuItem[]>(() => [
}
])

// Keybinding table logic
function commandLabel(commandId: string) {
return t(
`commands.${normalizeI18nKey(commandId)}.label`,
commandStore.getCommand(commandId)?.label ?? commandId
)
}

const commandsData = computed<KeybindingCommand[]>(() => {
return Object.values(commandStore.commands).map((command) => {
const keybindings = keybindingStore.getKeybindingsByCommandId(command.id)
Expand All @@ -236,10 +242,7 @@ const commandsData = computed<KeybindingCommand[]>(() => {
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
}
Expand Down Expand Up @@ -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)
})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
)
return
}
if (reset.changed) {
expandedCommandIds.value.delete(command.id)
await keybindingService.persistUserKeybindings()
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down Expand Up @@ -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'] = [
{
Expand Down
Loading
Loading