This PR fixes an issue with the `Combobox` component when using the
`virtual` mode.
We recently already fixed this issue
(https://github.com/tailwindlabs/headlessui/pull/3678) by applying a
patch on the `@tanstack/virtual-core` package. But this was only applied
in cjs builds, not in the esm builds.
Instead of trying to fix it in our build process, we decided to just fix
it upstream (https://github.com/TanStack/virtual/pull/1004) and this PR
bumps the version of `@tanstack/virtual-core` to the latest version
(which includes the fix).
This PR improves the performance of the `Combobox` component. This is a
similar implementation as:
- https://github.com/tailwindlabs/headlessui/pull/3685
- https://github.com/tailwindlabs/headlessui/pull/3688
Before this PR, the `Combobox` component is built in a way where all the
state lives in the `Combobox` itself. If state changes, everything
re-renders and re-computes the necessary derived state.
However, if you have a 1000 items, then every time the active item
changes, all 1000 items have to re-render.
To solve this, we can move the state outside of the `Combobox`
component, and "subscribe" to state changes using the `useSlice` hook
introduced in https://github.com/tailwindlabs/headlessui/pull/3684.
This will allow us to subscribe to a slice of the state, and only
re-render if the computed slice actually changes.
If the active item changes, only 3 things will happen:
1. The `ComboboxOptions` will re-render and have an updated
`aria-activedescendant`
2. The `ComboboxOption` that _was_ active, will re-render and the
`data-focus` attribute wil be removed.
3. The `ComboboxOption` that is now active, will re-render and the
`data-focus` attribute wil be added.
The `Combobox` component already has a `virtual` option if you want to
render many many more items. This is a bit of a different model where
all the options are passed in via an array instead of rendering all
`ComboboxOption` components immediately.
Because of this, I didn't want to batch the registration of the options
as part of this PR (similar to what we do in the `Menu` and `Listbox`)
because it behaves differently compared to what mode you are using
(virtual or not). Since not all components will be rendered, batching
the registration until everything is registered doesn't really make
sense in the general case. However, it does make sense in non-virtual
mode. But because of this difference, I didn't want to implement this as
part of this PR and increase the complexity of the PR even more.
Instead I will follow up with more PRs with more improvements. But the
key improvement of looking at the slice of the data is what makes the
biggest impact. This also means that we can do another release once this
is merged.
Last but not least, recently we fixed a bug where the `Combobox` in
`virtual` mode could crash if you search for an item that doesn't exist.
To solve it, we implemented a workaround in:
- https://github.com/tailwindlabs/headlessui/pull/3678
Which used a double `requestAnimationFrame` to delay the scrolling to
the item. While this solved this issue, this also caused visual flicker
when holding down your arrow keys.
I also fixed it in this PR by introducing `patch-package` and work
around the issue in the `@tanstack/virtual-core` package itself.
More info: 96f4da70b16d5cf259643
Before:
https://github.com/user-attachments/assets/132520d3-b4d6-42f9-9152-57427de20639
After:
https://github.com/user-attachments/assets/41f198fe-9326-42d1-a09f-077b60a9f65d
## Test plan
1. All tests still pass
2. Tested this in the browser with a 1000 items. In the videos below the
only thing I'm doing is holding down the `ArrowDown` key.
Before:
https://github.com/user-attachments/assets/945692a3-96e6-4ac7-bee0-36a1fd89172b
After:
https://github.com/user-attachments/assets/98a151d0-16cc-4823-811c-fcee0019937a
* use `act` from `react` instead of `@testing-library/react`
* bump dependencies
* bump `@testing-library/react`
* bump `@react-aria/interactions`
* bump "@tanstack/react-virtual"
* add `ResizeObserver` polyfill, and enable it by default for tests
* mock `getBoundingClientRect`
Otherwise the virtualization tests don't work as expected because they
rely on the client rect which is not supported (or not correctly
measured) in JSDOM.
* remove `nullable` prop
* prevent selecting active option on blur
+ cleanup and adjust comments
* remove nullable from comments
* bump TypeScript to 5.4
This gives us `NoInfer<T>`!
* simplify types of `Combobox`
Now that `nullable` is gone, we can take another look at the type
definition. This in combination with the new `NoInfer` type makes types
drastically simpler and more correct.
* re-add `nullable` to prevent type issues
But let's mark it as deprecated to hint that something changed.
* update changelog
* improve `ByComparator` type
If we are just checking for `T extends null`, then
`{id:1,name:string}|null` will also be true and therefore we would
eventually return `string` instead of `"id" | "name"`.
To solve this, we first check if `NonNullable<T> extends never`, this
would be the case if `T` is `null`.
Otherwise, we know it's not just `null` but it can be something else
with or without `null`. To be sure, we use `keyof NonNullable<null>` to
get rid of the `null` part and to only keep the rest of the object (if
it's an object).
* ensure the `by` prop type handles `multiple` values correctly
This way the `by` prop will still compare single values that are present
inside the array.
This now also solves a pending TypeScript issue that we used to `//
@ts-expect-error` before.
* type uncontrolled `Combobox` components correctly
We have some tests that use uncontrolled components which means that we
can't infer the type from the `value` type.
* simplify `onChange` calls
Now that we don't infer the type when using the generic inside of
`onChange`, it means that we can use `onChange={setValue}` directly
because we don't have to worry about the updater function of `setValue`
anymore.
* correctly type `onChange`, by adding `null`
If you are in single value mode, then the `onChange` can (and will)
receive `null` as a value (when you clear the input field). We never
properly typed it so this fixes that.
In multiple value mode this won't happen, if anything the value will be
`[]` but not `null`.
* remove `nullable` prop from playground
* drop `nullable` mentions in tests
* bump Next in playground
* convert legacy Link after Next.js bump
* update yarn.lock
* switch to npm workspaces
* move `packages/playground-*` to `playgrounds/*`
* use `npm` instead of `yarn`
* sync package-lock.json
* use node 20 for insiders releases
* sync yarn.lock
* drop resolutions from root package.json
This is done in the `package.json` from the `playground-react` package
* update next.config.js
Use `buildActivity` instead of `autoPrerender`
* ignore type checking in playground files
This is not ideal, but it is the first step in making the build pass
again.
* bump React & React DOM dependencies
* fix typo `TOmitableProps` → `TOmittableProps`
* bump prettier
* run prettier after prettier version bump
* bump TypeScript
* run prettier after TypeScript version bump
* enable `verbatimModuleSyntax`
This ensures all imported types are using the `type` keyword.
* add `type` to type related imports
* add common testing scenarios
Will be used in the new and existing components.
* add script to make Next.js happy
Right now Next.js does barrel file optimization and re-writing imports
to a real path in the `dist` folder. Most of those rewrites don't
actually exist because they have an assumption:
```js
import { FooBar } from '@headlessui/react'
```
is rewritten as:
```js
import { FooBar } from '@headlessui/react/dist/components/foo-bar/foo-bar'
```
This script will make sure these paths exist...
* improve `by` prop, introduce `useByComparator`
This hook has a default implementation when comparing objects. If the
object contains an `id`, then we will compare the objects by their
`id`'s without the user of the library needing to specify `by="id"`.
If the objects don't have an `id` prop, then the default is still to
compare by reference (unless specicified otherwise).
* sync yarn.lock
* rename `Features` to `HiddenFeatures` for `Hidden` component
* rename `Features` to `FocusTrapFeatures` in `FocusTrap` component
* rename `Features` to `RenderFeatures` in `render` util
* add `floating-ui` as a dependency + introduce internal floating related components
* bump Vue dependencies
* ensure scroll bar calculations can't go negative
* improve types in `@headlessui/vue`
* use snapshot tests for `Transition` tests in `@headlessui/vue`
* use snapshot tests for `portal` tests in `@headlessui/vue`
* rename `src/components/transitions/` to `src/components/transition/` (singular)
This is so that we can be consistent with the other components.
* drop custom `toMatchFormattedCss`, prefer snapshot tests instead
* use snapshot tests for `Label` tests in `@headlessui/vue`
* use snapshot tests for `Description` tests in `@headlessui/vue`
* sort exported components in tests for `@headlessui/vue`
* use snapshot tests in `@headlessui/tailwindcss`
* rename `mergeProps` to `mergePropsAdvanced`
This is a more complex version of a soon to be exported `mergeProps`
that we will be using in our components.
* do not expose `aria-labelledby` if it is only referencing itself
* expose boolean state as `kebab-case` instead of `camelCase`
These are the ones being exposed inside `data-headlessui-state="..."`
* expose boolean data attributes
A slot with `{active,focus,hover}` will be exposed as:
```html
<span data-headlessui-state="active focus hover"></span>
```
But also as boolean attributes:
```html
<span data-active data-focus data-hover></span>
```
* improve internal types for `className` in `render` util
* ensure we keep exposed data attributes into account when trying to forward them to the component inside the `Fragment`
* add small typescript type fix
This is internal code, and the public API is not influenced by this
`:any`. It does make TypeScript happy.
* introduce `mergeProps` util to be used in our components
This will help us to merge props, when event handlers are available they
will be merged by wrapping them in a function such that both (or more)
event handlers are called for the same `event`.
* add new internal `Modal` component
* fix: when using `Focus.Previous` with `activeIndex = -1` should start at the end
* prefer `window.scrollY` instead of `window.pageYOffset`
Because `window.pageYOffset` is deprecated.
* add `'use client'` directives on client only components
These components use hooks that won't work in server components and you
will receive an error otherwise.
* drop `import 'client-only'` in favor of the `'use client'` directive
* add React Aria dependencies
* pin beta dependencies
* prettier bump formatting
* improve TypeScript types in tests
* use new Jest matchers instead of deprecated ones
* improve typescript types in Vue
* prefer `useLabelledBy` and `useDescribedBy`
* add internal `DisabledProvider`
* add internal `IdProvider`
* add internal `useDidElementMove` hook
* add internal `useElementSize` hook
* add internal `useIsTouchDevice` hook
* add internal `useActivePress` hook
* use snapshot tests for `Description` tests
* use snapshot tests for `Label` tests
* use snapshot tests for `Portal` tests
* use snapshot tests for `render` tests
* add (private) `Tooltip` component
Currently this one is not ready yet, so its not publicly exposed yet.
* add internal `FormFields` component
This one adds a component to render (hidden) inputs for native form
support. It also ensures that form fields can be hoisted to the end of
the nearest `Field`. If the components are not inside a `Field` they
will be rendered in place.
* add new `Button` component
* add new `Checkbox` component
* add new `DataInteractive` component
* add new `Field` component
* add new `Fieldset` component
* add new `Legend` component
* add new `Input` component
* add new `Select` component
* add new `Textarea` component
* export new components
* WIP
* remove `within: true`
This only makes sense if anything inside the current element receives
focus, which is not the case for `input`, `select`, `textarea` or
`Radio/RadioOption`.
* group focus/hover/active hooks together
* conditionally link anchor panel
* immediately focus the container
* prevent premature disabling of `Listbox`'s floating integration
+ Track whether the button moved or not when disabling such that we can
disable the transitions earlier.
* improve scroll locking on iOS
* skip hydration tests for now
* skip certain focus trap tests for now
* update CHANGELOG.md
* add missing requires
* drop unused `@ts-expect-error`
* ignore type issues in playgrounds
These playgrounds are mainly test playgrounds. Lower priority for now,
we will get back to them.
* add yarn resolutions to solve swc bug
* add `prettier-plugin-organize-imports` and `prettier-plugin-tailwindcss`
* format
* bump Tailwind CSS
* format playgrounds using updated Tailwind CSS and Prettier plugins
* use import syntax
* add scripts to help with automating releases
* add prepare-release and release workflows
* bump actions from v2 to v3
* use `github.ref_name` for getting the tag name
* ensure we use `**` for matching tags with slashes in them
* prevent scrolling the page when using arrow keys in
* update changelog
* bump prettier
Does GitHub Actions have an incorrect cache somehow?
* use Active LTS in CI
* bump dev dependencies to React 18
* setup Jest to include `IS_REACT_ACT_ENVIRONMENT`
* prefer `useId` from React 18 if it exists
In React 16 & 17, where `useId` doesn't exist, we will fallback to our
implementation we have been using up until now.
The `useId` exposed by React 18, ensures stable references even in SSR
environments.
* update expected events
React 18 now uses the proper events:
- `blur` -> `focusout`
- `focus` -> `focusin`
* ensure to wait a bit longer
This is a bit unfortunate, but since React 18 now does an extra
unmount/remount in `StrictMode` to ensure that your code is
ConcurrentMode ready, it takes a bit longer to settle what the DOM sees.
That said, this is a temporary "hack". We are going to experiment with
using tools like Puppeteer/Playwright to run our tests in an actual
browser instead to eliminate all the weird details that we have to keep
in mind.
* prefer `.focus()` over `fireEvent.focus(el)`
* abstract `microTask` polyfill code
* prefer our `focus(el)` function over `el.focus()`
Internally we would still use `el.focus()`, but this allows us to have
more control over that `focus` function.
* add React 18 to the React Playground
* improve hooks for React 18
- Improving the cleanup of useEffect hooks
- useIsoMorphicEffect instead of normal useEffect, so that we can use
useLayoutEffect to be a bit quicker.
* improve disposables
- This allows us to add event listeners on a node, and get automatic
cleanup once `dispose` gets called.
- We also return all the `d.add` calls, so that we can cleanup specific
parts only instead of everything or nothing.
* reimplement the Transition component to be React 18 ready
* wait an additional frame for everything to settle
* update playground examples
* suppressConsoleLogs for RadioGroup components
* update changelog
* keep the `to` classes for a smoother transition
In the next transition we will remove _all_ classes provided and re-add
the once we need.
---
Some extra special thanks:
- Thanks @silvenon for your initial work on the `transition` events in #926
- Thanks @thecrypticace for doing late-night debugging sessions
Co-authored-by: =?UTF-8?q?Matija=20Marohni=C4=87?= <matija.marohnic@gmail.com>
Co-authored-by: Jordan Pittman <jordan@cryptica.me>
* improve Tree Shaking in ESM
Instead of bundling everything into a single ESM file, we generate every
single file as ESM. This is what we did in 1.4.x as well.
I would expect if your library had a single ESM file and you only used 1
function that the application you use it in correctly does the
tree-shakign for you. Apparantly a lot of applications are not properly
setup for this, so let's create multiple files instead.
* update changelog
* Add combobox to Vue playground
* Update input props
* Wire up input event for changes
This fires changes whenever you type, not just on blur
* Fix playground
* Don't fire input event when pressing escape
The input event is only supposed to fire when the .value of the input changes. Pressing escape doesn't change the value of the input directly so it shouldn't fire.
* Add latest active option render prop
* Add missing active option props to Vue version
* cleanup
* Move test
* Fix error
* Add latest active option to Vue version
* Tweak active option to not re-render
* Remove refocusing on outside mousedown
* Update tests
* Forward refs on combobox to children
* Cleanup code a bit
* Fix lint problems on commit
* Fix typescript issues
* Update changelog
This used to also build the individual playground packages but that's
not needed on CI (nor locally). Because Vercel will build them for us.
This will safe us some time on CI, since we can run them in parallel now
and only build the actual libraries.
* use esbuild for React instead of tsdx
* remove tsdx from Vue
* use consistent names
* add jest and prettier
* update scripts
* ignore some folders for prettier
* run lint script instead of tsdx lint
* run prettier en-masse
This has a few changes because of the new prettier version.
* bump typescript to latest version
* make typescript happy
* cleanup playground package.json
* make esbuild a dev dependency
* make scripts consistent
* fix husky hooks
* add dedicated watch script
* add `yarn playground-react` and `yarn react-playground` (alias)
This will make sure to run a watcher for the actual @headlessui/react
package, and start a development server in the playground-react package.
* ignore formatting in the .next folder
* run prettier on playground-react package
* setup playground-vue
Still not 100% working, but getting there!
* add playground aliases in @headlessui/vue and @headlessui/react
This allows you to run `yarn react playground` or `yarn vue playground`
from the root.
* add `clean` script
* move examples folder in playground-vue to root
* ensure new lines for consistency in scripts
* fix typescript issue
* fix typescript issues in playgrounds
* make sure to run prettier on everything it can
* run prettier on all files
* improve error output
If you minify the code, then it could happen that the errors are a bit
obscure. This will hardcode the component name to improve errors.
* add the `prettier-plugin-tailwindcss` plugin, party!
* update changelog
* start of combobox
* start with a copy of the Listbox
* WIP
* Add Vue Combobox
* Update Vue version of combobox
* Update tests
* Fix typescript errors in combobox test
* Fix input label
The spec says that the combobox itself is labelled directly by the associated label. The button can however be labelled by the label or itself.
* Add active descendant to combobox/input
* Add listbox role to comobox options
Right now the option list *is* just a listbox. If we were to allow other types in the future this will need to be changable
* Update tests
* move React playground to dedicated package
* add react playground script to root
* ensure we only open/close the combobox when necessary
* ensure export order is correct
* remove leftover pages directory from React package
* Only add aria controls when combobox is open
* add missing next commands
* make typescript happy
* build @headlessui/react before building playground-react
* add empty public folder
This makes vercel happy
* wip
* Add todo
* Update tests
Still more updates to do but some are blocked on implementation
* change default combobox example slightly
* ensure that we sync the input with new state
When the <Combobox value={...} /> changes, then the input should change
as well.
* only sync the value with the input in a single spot
* WIP: object value to string
* WIP
* WIP
* WIP groups
* Add static search filtering to combobox
* Move mouse leave event to combobox
* Fix use in fragments
* Update
* WIP
* make all tests pass for the combobox in React
* remove unnecessary playground item
* remove listbox wip
* only fire change event on inputs
Potentially we also have to do this for all kinds of form inputs. But
this will do for now.
* disable combobox vue tests
* Fix vue typescript errors
* Vue tests WIP
* improve combobox playgrounds a tiny bit
* ensure to lookup the correct value
* make sure that we are using a div instead of a Fragment
* expose `activeItem`
This will be similar to `yourData[activeIndex]`, but in this case the
active option's data. Can probably rename this if necessary!
* Update comments
* Port react tests to Vue
* Vue tests WIP
* WIP
* Rename activeItem to activeOption
* Move display value to input
* Update playgrounds
* Remove static filtering
* Add tests for display value
* WIP Vue Tests
* WIP
* unfocus suite
* Cleanup react accessibility assertions code
* Vue WIP
* Cleanup errors in react interactions test utils
* Update vue implementation
closer :D
* Fix searching
* Update
* Add display value stubs
* Update tests
* move `<Combobox onSearch={} />` to `<Combobox.Input onChange={} />`
* use `useLatestValue` hook
* make `onChange` explicitly required
* remove unused variables
* move `<Combobox @search="" />` to `<ComboboxInput @change="" />`
* use correct event
* use `let` for consistency
* remove unnecessary hidden check
* implement displayValue for Vue
* update playground to reflect changes
* make sure that the activeOptionIndex stays correct
* update changelog
Co-authored-by: Jordan Pittman <jordan@cryptica.me>
* add watch script
* make interactions in Vue and React consistent
* re-work focus restoration
When we click outside of the Menu or Listbox, we want to
restore the focus to the Button, *unless* we clicked on/in an element
that is focusable in itself. For example, when the Menu is open and you
click in an input field, the input field should stay focused. We should
also close the Menu itself at this point.
* add examples with multiple elements
* bump dependencies
* add unmount strategy to README (React)
* add unmount strategy to README (Vue)
* add different render features (React)
* use render features in Menu and Listbox (React)
* add different render features (Vue)
* use render features in Menu and Listbox (Vue)
* bump dependencies
* add ability to change the ref property using `refName`
Example use case:
```tsx
// Some components have this API with an `innerRef`. The suggested approach is to use
// `React.forwardRef` so that you get the actual `ref` value. However if you already have this
// `innerRef` API than we can use the `refName="innerRef"` to give the `ref` prop a good name. It
// defaults to `ref` so that it still works everywhere else.
function MyButton({ innerRef, ...props }) {
return <button ref={innerRef} {...props} />
}
<Menu.Button as={MyButton} refName="innerRef" />
```
* small cleanup, move refs to props we control
* add tests for the render abstraction (Render)
+ use the unique __ symbol as a default value in the Props type for the
omitable props.
* use render features in Transition (React)
* add/update Transition examples to also showcase the `unmount={false}` render strategy
* bump dependencies
* add example with nested unmount/hide transitions
* add unmount to Transition documentation
* make jest monorepo aware
* add @testing-library/jest-dom for custom matchers
This way we can use expect(element).toHaveAttribute(key, value?)
* abstract keys enum
* change type to unknown, because we don't know the return value
* update use-id hook, make it suspense aware
Thanks Reach UI!
* hoist the disposables collection
* add accessbility assertions for listbox
Also made it consistent for the Menu component and simplified some of the assertions
* add use-computed hook
This allows us re-render when hooks change, but also return a value. So this is a combination of useEffect and a useState value.
* add Listbox component
* bump dependencies
* add listbox example
* add lint-staged
This way we will only lint the files that have been staged and ready to be committed instead of the whole codebase
* add missing prevent defaults
* improve tests to verify that we can actually update the value of the listbox
* scroll the active listbox item into view
* small optimization, only focus "Nothing" on pointer leave when we are the active item
We used to always go to "Nothing" on pointer leave. And while this code
doesn't get called often, it *gets* called if you are using your arrow
keys and the mouse pointer is still over the list.
* bump dependencies
Also moved the tailwind dependencies to the root
* fix typo
* drop the default Transition inside the Menu and Listbox components
* update examples to reflect drop of default Transition wrapper
* rename Listbox.{Items,Item} to Listbox.{Options,Option}
Also rename all instances of `item` to `option` in tests and comments
and what have you...
* fix typo
* drop disabled prop, use aria-disabled only