Skip to content

Commit

Permalink
fix: only scroll into view on first render and via keyboard (#135)
Browse files Browse the repository at this point in the history
* fix: only scroll into view on first render and via keyboard

* refactor: remove unnecessary code

---------

Co-authored-by: João Pedro Magalhães <[email protected]>
  • Loading branch information
joaom00 and João Pedro Magalhães authored Jan 30, 2024
1 parent b768f2b commit 9b97580
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions cmdk/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,14 @@ const Command = React.forwardRef<HTMLDivElement, CommandProps>((props, forwarded
if (value !== undefined) {
const v = value.trim().toLowerCase()
state.current.value = v
schedule(6, scrollSelectedIntoView)
store.emit()
}
}, [value])

useLayoutEffect(() => {
schedule(6, scrollSelectedIntoView)
}, [])

const store: Store = React.useMemo(() => {
return {
subscribe: (cb) => {
Expand All @@ -218,15 +221,16 @@ const Command = React.forwardRef<HTMLDivElement, CommandProps>((props, forwarded
sort()
schedule(1, selectFirstItem)
} else if (key === 'value') {
// opts is a boolean referring to whether it should NOT be scrolled into view
if (!opts) {
// Scroll the selected item into view
schedule(5, scrollSelectedIntoView)
}
if (propsRef.current?.value !== undefined) {
// If controlled, just call the callback instead of updating state internally
const newValue = (value ?? '') as string
propsRef.current.onValueChange?.(newValue)
return
// opts is a boolean referring to whether it should NOT be scrolled into view
} else if (!opts) {
// Scroll the selected item into view
schedule(5, scrollSelectedIntoView)
}
}

Expand Down

0 comments on commit 9b97580

Please sign in to comment.