diff --git a/.changeset/fix-combobox-auto-focus.md b/.changeset/fix-combobox-auto-focus.md new file mode 100644 index 000000000..54b98e4d5 --- /dev/null +++ b/.changeset/fix-combobox-auto-focus.md @@ -0,0 +1,5 @@ +--- +"@cube-dev/ui-kit": patch +--- + +Fix ComboBox auto-focus behavior when using `allowsCustomValue`. The component now correctly maintains focus on the first filtered item while typing, allowing Enter key selection to work properly. The focus is automatically re-established when the currently focused item is filtered out of the list. Additionally, the refocus logic now properly verifies that the selected item exists in the filtered collection before attempting to focus on it, preventing focus on non-existent keys. diff --git a/.cursor/worktrees.json b/.cursor/worktrees.json new file mode 100644 index 000000000..150c5dc53 --- /dev/null +++ b/.cursor/worktrees.json @@ -0,0 +1,5 @@ +{ + "setup-worktree": [ + "pnpm install" + ] +} \ No newline at end of file diff --git a/src/components/fields/ComboBox/ComboBox.tsx b/src/components/fields/ComboBox/ComboBox.tsx index 57265d244..f704f5bfc 100644 --- a/src/components/fields/ComboBox/ComboBox.tsx +++ b/src/components/fields/ComboBox/ComboBox.tsx @@ -1665,10 +1665,39 @@ export const ComboBox = forwardRef(function ComboBox( if (lastFocusSourceRef) lastFocusSourceRef.current = 'keyboard'; - if (selectionManager.focusedKey == null) { - const keyToFocus = - effectiveSelectedKey != null ? effectiveSelectedKey : collectFirstKey(); - if (keyToFocus != null) selectionManager.setFocusedKey(keyToFocus); + // Check if we need to set or update focus + const currentFocusedKey = selectionManager.focusedKey; + let needsRefocus = false; + + if (currentFocusedKey == null) { + // No focus at all - need to set initial focus + needsRefocus = true; + } else { + // Check if currently focused key still exists in the collection + const focusedItemExists = collection.getItem(currentFocusedKey) != null; + if (!focusedItemExists) { + // Focused item was filtered out - need to refocus + needsRefocus = true; + } + } + + if (needsRefocus) { + let keyToFocus: Key | null = null; + + // First try to focus on the selected key if it exists in the collection + if ( + effectiveSelectedKey != null && + collection.getItem(effectiveSelectedKey) != null + ) { + keyToFocus = effectiveSelectedKey; + } else { + // Fall back to the first key in the collection + keyToFocus = collectFirstKey(); + } + + if (keyToFocus != null) { + selectionManager.setFocusedKey(keyToFocus); + } } }, [shouldShowPopover, effectiveSelectedKey]);