pacocoursey / cmdk

Fast, unstyled command menu React component.
https://cmdk.paco.me
MIT License
9.03k stars 258 forks source link

Filtering & scrolling into view dysfunction 🀔 #233

Open najdic opened 3 months ago

najdic commented 3 months ago

Hello,

First and foremost, I want to express my appreciation for the tremendous work on cmdk 🚀

However, I've encountered a potential issue involving filtering and/or scrolling into view functionality in my recent use case. While the library generally performs admirably, I've noticed some unexpected behavior when filtering "large" datasets, seems like the selected element is not always in the view 🀔

Sandbox: https://codesandbox.io/p/sandbox/beautiful-khayyam-chp8y3

CMDK Version: ^1.0.0

https://github.com/pacocoursey/cmdk/assets/50749219/400cc0a5-58ee-42aa-b15a-de78461ecc9f

import { useEffect, useState } from "react";
import { Command } from "cmdk";

export default function App() {
  const [countries, setCountries] = useState<string[]>([]);

  useEffect(() => {
    async function fetchCountries() {
      type Country = { name: { common: string } };

      const response = await fetch("https://restcountries.com/v3.1/all");
      const data: Country[] = await response.json();

      const countries = data.map((country) => country.name.common);
      setCountries(countries);
    }

    fetchCountries();
  }, []);

  return (
    <div className="App">
      <Command label="Command Menu">
        <Command.Input
          autoFocus
          placeholder="Search..."
          className="text-neutral-400 outline outline-2 mb-2"
        />

        <Command.List className="max-h-[400px] overflow-y-auto overflow-x-hidden">
          <Command.Empty>:/</Command.Empty>

          <Command.Group>
            {countries.map((country) => (
              <Command.Item
                key={country}
                value={country}
                className="flex gap-2 text-neutral-400 aria-selected:text-neutral-800 aria-selected:bg-red-400"
              >
                <img alt="" src="https://placehold.co/20x20" />
                {country}
              </Command.Item>
            ))}
          </Command.Group>
        </Command.List>
      </Command>
    </div>
  );
}
fkhadra commented 3 months ago

Hey @najdic, I've encountered the same issue, it seems to occurs whenever the list trigger the overflow. I haven't looked into it more but I'll share the workaround i'm using for now.

// 1. create a ref
const listRef = useRef<HTMLDivElement>(null);
const scrollId = useRef<ReturnType<typeof setTimeout>>();

// 2. attach it to your list
<Command.List ref={listRef}>

// 3. listen for value changes on the input
<Command.Input  onValueChange={() => {
               // clear pending scroll
                clearTimeout(scrollId.current);

                // the setTimeout is used to create a new task
                // this is to make sure that we don't scroll until the user is done typing
                // you can tweak the timeout duration ofc
                scrollId.current = setTimeout(() => {
                  // inside your list select the first group and scroll to the top
                  listRef.current?.querySelector("[cmdk-group]")?.scrollTo({ top: 0 });
                }, 0);
              }}
 />
dphuang2 commented 3 months ago

For anybody using shadcn/ui, you can use this onValueChange function instead:

// clear pending scroll
clearTimeout(scrollId.current);

// the setTimeout is used to create a new task
// this is to make sure that we don't scroll until the user is done typing
// you can tweak the timeout duration ofc
scrollId.current = setTimeout(() => {
  // inside your list select the first group and scroll to the top
  const div = listRef.current;
  div?.scrollTo({ top: 0 });
}, 0);
benjosua commented 1 month ago

@dphuang2 could you share a component with this implemented?