Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filtering & scrolling into view dysfunction 馃 #233

Open
najdic opened this issue Mar 11, 2024 · 3 comments
Open

Filtering & scrolling into view dysfunction 馃 #233

najdic opened this issue Mar 11, 2024 · 3 comments

Comments

@najdic
Copy link

najdic commented Mar 11, 2024

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

Screen.Recording.2024-03-11.at.15.17.02.mov
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
Copy link

fkhadra commented Mar 12, 2024

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
Copy link

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
Copy link

@dphuang2 could you share a component with this implemented?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants