Skip to content

Commit

Permalink
arrow keys wrap around (#57)
Browse files Browse the repository at this point in the history
* arrow keys wrap around

* make wraparound dependent on loop prop

* document loop prop

* prettier formatting
  • Loading branch information
Kilian authored Nov 16, 2022
1 parent 15b0c3d commit 994dea6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,10 @@ Or disable filtering and sorting entirely:
</Command>
```

You can make the arrow keys wrap around the list (when you reach the end, it goes back to the first item) by setting the `loop` prop:

<Command loop />

### Dialog `[cmdk-dialog]` `[cmdk-overlay]`

Props are forwarded to [Command](#command-cmdk-root). Composes Radix UI's Dialog component. The overlay is always rendered. See the [Radix Documentation](https://www.radix-ui.com/docs/primitives/components/dialog) for more information. Can be controlled with the `open` and `onOpenChange` props.
Expand Down
16 changes: 15 additions & 1 deletion cmdk/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ type CommandProps = Children &
* Event handler called when the selected item of the menu changes.
*/
onValueChange?: (value: string) => void
/**
* Optionally set to `true` to turn on looping around when using the arrow keys.
*/
loop?: boolean
}

type Context = {
Expand Down Expand Up @@ -419,7 +423,17 @@ const Command = React.forwardRef<HTMLDivElement, CommandProps>((props, forwarded
const index = items.findIndex((item) => item === selected)

// Get item at this index
const newSelected = items[index + change]
let newSelected = items[index + change]

if (propsRef.current?.loop) {
newSelected =
index + change < 0
? items[items.length - 1]
: index + change === items.length
? items[0]
: items[index + change]
}

if (newSelected) store.setState('value', newSelected.getAttribute(VALUE_ATTR))
}

Expand Down

1 comment on commit 994dea6

@vercel
Copy link

@vercel vercel bot commented on 994dea6 Nov 16, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

cmdk-website – ./

cmdk.vercel.app
cmdk-website-paco.vercel.app
cmdk.paco.me
cmdk-website-git-main-paco.vercel.app

Please sign in to comment.