* 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
* ensure `appear` works in combination with SSR
* add appear transition example
* update changelog
* add scale to appear example
* trigger immediate transition once the DOM is ready
* ensure React doesn't change the `className` underneath us
* handle all base classes
We are bypassing React when handling classes in the Transition
component. Let's ensure the base classes from the prop are also added
correctly.
* add missing `base` to tests
* simplify `useTransition` hook
* add react-hot-toast example
* make TS happy
* ensure the `classNames` are unique
* remove classNames if it results in an empty string
This will ensure that we don't end up with `class=""` in the DOM
* ensure `unmount` is defaulting to `true`
* do not read from `prevShow` in render
After fixing the other bugs, this part only caused bugs right now. Even
when re-rendering the Transition component while transitioning. Dropping
this fixes that behaviour.
* extend `appear` demo with appear, show, unmount booleans
+ a `lazily` one to mimic a conditional render on the client instead of
a fresh page refresh.
* disable smooth scrolling when opening/closing Dialogs
For iOS workaround related purposes we have to capture the scroll
position and offset the margin top with that amount and then
`scrollTo(0,0,)` to prevent all kinds of funny UI jumps.
However, if you have `scroll-behavior: smooth` enabled on your `html`,
then offseting the margin-top and later `scrollTo(0,0)` would be
handled in a smooth way, which means that the actual position would be
off.
To solve this, we disable smooth scrolling entirely in order to make the
position of the Dialog correct. This shouldn't be a problem in practice
since the page itself isn't suppose to scroll anyway.
Once the Dialog closes we reset it such that everything else keeps
working as expected in a (smooth) way.
* add `microTask` to disposables
* ensure the fix works in React's double rendering dev mode
* update changelog
* Only use useServerHandoffComplete in React < 18
It’s only useful for the useId hook. It is not compatible with `<Suspense>` because hydration is delayed then.
* Make sure portals first render matches the server by rendering nothing
Since Portals cannot SSR the first render MUST also return `null`. React really needs an `isHydrating` API.
* Lazily resolve root containers
This fixes a problem where clicks were assumed to be outside because of the delayed `<Portal>` render. The second portal render doesn’t cause the dialog to re-render thus the initial ref values were stale.
* Update changelog
---------
Co-authored-by: Robin Malfait <malfait.robin@gmail.com>
* only render `<MainTreeNode />` in `Popover.Group` instead of after every `Popover`
* make Vue Popover consistent
* apply same `MainTreeNode` logic to Vue version
* update changelog
* listen for both `mousedown` and `pointerdown` events
This is necessary for calculating the target where the focus will
eventually move to. Some other libraries will use an
`event.preventDefault()` and if we are not listening for all "down"
events then we might not capture the necessary target.
We already tried to ensure this was always captured by using the
`capture` phase of the event but that's not enough.
This change won't be enough on its own, but this will improve the
experience with certain 3rd party libraries already.
* refactor one-liners
* listen for `touchend` event to improve "outside click" on mobile devices
* update changelog
* abstract resolving root containers to hook
This way we can reuse it in other components when needed.
* allow registering a `Portal` component to a parent
This allows us to find all the `Portal` components that are nested in a
given component without manually adding refs to every `Portal` component
itself.
This will come in handy in the `Popover` component where we will allow
focus in the child `Portal` components otherwise a focus outside of the
`Popover` will close the it. In other components we often crawl the DOM
directly using `[data-headlessui-portal]` data attributes, however this
will fetch _all_ the `Portal` components, not the ones that started in
the current component.
* allow focus in portalled containers
The `Popover` component will close by default if focus is moved outside
of it. However, if you use a `Portal` comopnent inside the
`Popover.Panel` then from a DOM perspective you are moving the focus
outside of the `Popover.Panel`. This prevents the closing, and allows
the focus into the `Portal`.
It currently only allows for `Portal` components that originated from
the `Popover` component. This means that if you open a `Dialog`
component from within the `Popover` component, the `Dialog` already
renders a `Portal` but since this is part of the `Dialog` and not the
`Popover` it will close the `Popover` when focus is moved to the
`Dialog` component.
* ensure `useNestedPortals` register/unregister with the parent
This ensures that if you have a structure like this:
```jsx
<Dialog> {/* Renders a portal internally */}
<Popover>
<Portal> {/* First level */}
<Popover.Panel>
<Menu>
<Portal> {/* Second level */}
<Menu.Items>
{/* ... */}
</Menu.Items>
</Portal>
</Menu>
</Popover.Panel>
</Portal>
</Popover>
</Dialog>
```
That working with the `Menu` doesn't close the `Popover` or the `Dialog`.
* cleanup `useRootContainers` hook
This will allow you to pass in portal elements as well. + cleanup of
the resolving of all DOM nodes.
* handle nested portals in `Dialog` component
* expose `contains` function from `useRootContainers`
Shorthand to check if any of the root containers contains the given
element.
* add tests to verify that actions in `Portal` components won't close the `Popover`
* update changelog
* re-order use-outside-click logic
To make it similar between React & Vue
* inject the `PortalWrapper` context in the correct spot
* ensure to forward the incoming `attrs`
* add `get-text-value` helper
* use `getTextValue` in `Listbox` component
* use `getTextValue` in `Menu` component
* update changelog
* ensure we handle multiple values for `aria-labelledby`
* hoist regex
* drop child nodes instead of replacing its innerText
This makes it a bit slower but also more correct. We can use a cache on
another level to ensure that we are not creating useless work.
* add `useTextValue` to improve performance of `getTextValue`
This will add a cache and only if the `innerText` changes, only then
will we calculate the new text value.
* use better `useTextValue` hook
* fix(tabs): wrong tab focus when Tab contains a Dialog
* refactor(focus-trap): rename variable and move logic
* test(tabs): improve test by asserting the active element
* ensure `FocusTrap` is not active when `enabled = false`
* fix: move the enabled check to unmounting
* refactor to `useOnUnmount` hook
This will allow us to make the code relatively similar between React and
Vue.
* update changelog
---------
Co-authored-by: Robin Malfait <malfait.robin@gmail.com>
* drop `@ts-expect-error`, because `inert` is available now
* fix logical error
We want to apply `inert` when we _don't_ have nested dialogs, because if
we _do_ have nested dialogs, then the inert should be applied from the
nested dialog (or visually the top most dialog).
* update changelog
* replace `useInertOthers` with `useInert`
* add `assertInert` and `assertNotInert` accessibility assertion helpers
* ensure the `main tree` root is marked as inert
As well as the parent dialogs in case of nested dialogs.
* introduce `opening` and `closing` states
Also represent them as bits so that we can easily combine them while we
are transitioning from one state to the other.
* update `open/closed` state checks
Instead of checking whether it is in one state or an other, we can check
if the current state contains some potential sub-state.
This allows us to still check if we are in the `Open` state, while also
`Closing` because the state will be `S.Open | S.Closing`.
* expose `flags` from the `useFlags` hook
* add the `Closing` and `Opening` states to the Open/Closed state
* create dedicated `abcEnabled` variables
* keep the `State.Closing` into account for `scroll locking` and `inert others`
* add a test for the `Closing` state impacting the `Dialog` component
* cleanup unused imports
* add `unmount` util to the Vue Test renderer
* update changelog
* use the `import * as React from 'react'` pattern
We use named imports, but we have to import `React` itself as well for
JSX because it compiles to `React.createElement`. We could get rid of
our own JSX and use it directly, or we can use this `import * as React
from 'react'` syntax.
This fixes an issue for people using `allowSyntheticDefaultImports: false` in TypeScript.
Fixes: #2117
* update changelog
* Fix overflow when swapping dialogs that use transition
* Refactor
* refactor
* wip
* wip
* wip
* wip
* wip
* wip
* wip
* wip
* Inline shim for ESM support
Until the official package adds an ESM version with a wildcard import we can’t use it. This version was copied from Remix Router
* Add dialog shadow root examples
* Fix SSR error
* Add repro for iOS scrolling issue
* Try to fix vercel build
idk what’s wrong here
* Update repro
A transition is required to delay closing enough to demonstrate the bug
* Port global dialog state to Vue
* Add dialog test to Vue
* wip
* wip
* Workaround bug
This shouldn’t happen at all and we need to find the source of the bug but this should “fix” things for the time being
* wip
* Rebuild overflow locking with simpler API
* wip
* wip
* wip
* wip
* wip
* wip
* wip
* wip
* wip
* Update deps
* wip
* simplify
* Port to Vue
* wip
* wip
* Tweak tests
* Update changelog
* Ensure meta callbacks are cleaned up
* cleanup
* wip
* Allow clicks inside dialog panel when target is inside shadow root
* Introduce resettable “server” state
This will aid in testing
* Add SSR and hydration tests for react
* Fix server rendering of Tabs on React 17
* Fix CS
* Skip hydration tests
* Tweak SSR implementation in Vue
* Update changelog
* remove `transitioncancel` logic
On Desktop Sarai, Chrome, and on mobile iOS Safari the
`transitioncancel` is never called on outside click of the Dialog.
However, on mobile Android Chrome it _is_ called, and the
`transitionend` is never triggered for _some_ reason.
According to the MDN docs:
> If the transitioncancel event is fired, the transitionend event will not fire.
>
> — https://developer.mozilla.org/en-US/docs/Web/API/Element/transitioncancel_event
When testing this, I never got into the `transitionend` when I got into
the `transitioncancel` first. But, once I removed the `transitioncancel`
logic, the `transitionend` code _was_ being called.
The code is now both simpler, and works again. The nice part is that we
never did anything with the `cancel` event. We marked it as done using
the `Reason.Cancelled` and that's about it.
* cleanup transition completion `Reason`
* update changelog
* improve tracking of transitionableChildren
* remove weird outlier snapshots
If anything is still wrong the tests will still fail but the diffs will
be easier to read.
* remove event handling from `useTransition`
* handle before/after events in `Transition` directly
* fix incorrect logic bug in tests
* add very explicit test for transition event order
* ignore flakey tests for now
We will get back to these!
* ensure cancellation of transitions works properly
* update changelog
* ensure `syncInputValue` is updated correctly
* WIP
* WIP
* Don’t resync on open
* Fix react value syncing
update
* Add comment
* Port new setup over to Vue
* Remove `inputPropsRef`
We hardly knew ye
* Remove repro
* Cleanup
* Update changelog
Co-authored-by: Robin Malfait <malfait.robin@gmail.com>
* implement uncontrolled form components
A few versions ago we introduced compatibility with the native `form`
element. This means that behind the scenes we render hidden inputs that
are kept in sync which allows you to submit your normal form and get
data via `new FormData(event.currentTarget)`.
Before this change every form related component (Switch, RadioGroup,
Listbox and Combobox) always had to be passed a `value` and an
`onChange` regardless of this change.
This change will allow you to not even use the `value` and the
`onChange` at all and keep it completely uncontrolled.
This has some changes:
- `value` is made optional
- `onChange` is made optional (but will still be called if passed
regardless of being controlled or uncontrolled)
- `defaultValue` got added so that you can still pre-fill your values
with known values.
- `value` render prop got exposed so that you can still use this while
rendering.
This should also make it completely compatible with tools like Remix
without wiring up your own state.
* update example combinations/form playground to use uncontrolled
components
* improve types, add missing render prop arguments
* add tests for uncontrolled components (React)
* implement uncontrolled form elements in Vue
* ensure outside click works on Safari in iOS
When tapping on an element that is not clickable (like a div), then the
`click` and `mousedown` events will not reach the
`window.addEventListener('click')` listeners.
The only event that does that could be interesting for us is the
`pointerdown` event. The issue with this one is that we then run into
the big issue we ran in a few months ago where clicks on a scrollbar
*also* fired while a click doesn't.
This issue was not an issue in React land, the
`window.addEventListener('click')` was fired even when tapping on a
`div`. This was very very confusing, but we think this is because of the
syntethic event system, where the event listener is added to the root of
your application (E.g.: #app) and React manually bubbles the events.
Because this is done manually, it *does* reach the window as well.
The confusing part is, how does React convert a `pointerdown` event to a
`mousedown` and `click`. There is no code for that in their codebase?
Turns out they don't, and turns out the events **do** bubble, but up
until the `document`, not the `window`. But since they are manually
bubbling events it all makes sense.
So the solution? Let's switch from `window` to `document`...
* update Dialog example to use DialogPanel
* update changelog
* Don’t close dialog if opened during mouse up event
* Don’t close dialog if drag starts inside dialog and ends outside dialog
* Handle closing of nested dialogs that are always mounted
* Fix focus trap restoration in Vue
* Update changelog
* check typeof document in addition to typeof window
* remove unused import
* Extract SSR check to a central spot
* Fix CS
* Update changelog
Co-authored-by: Jordan Pittman <jordan@cryptica.me>
* convert dialog in playground to use Dialog.Panel
* convert `tabs-in-dialog` example to use `Dialog.Panel`
* add scrollable dialog example to the playground
* simplify `outside click` behaviour
Here is a little story. We used to use the `click` event listener on the
window to try and detect whether we clicked outside of the main area we
are working in.
This all worked fine, until we got a bug report that it didn't work
properly on Mobile, especially iOS. After a bit of debugging we switched
this behaviour to use `pointerdown` instead of the `click` event
listener. Worked great! Maybe...
The reason the `click` didn't work was because of another bug fix. In
React if you render a `<form><Dialog></form>` and your `Dialog` contains
a button without a type, (or an input where you press enter) then the
form would submit... even though we portalled the `Dialog` to a
different location, but it bubbled the event up via the SyntethicEvent
System. To fix this, we've added a "simple" `onClick(e) { e.stopPropagation() }`
to make sure that click events didn't leak out.
Alright no worries, but, now that we switched to `pointerdown` we got
another bug report that it didn't work on older iOS devices. Fine, let's
add a `mousedown` next to the `pointerdown` event. Now this works all
great! Maybe...
This doesn't work quite as we expected because it could happen that both
events fire and then the `onClose` of the Dialog component would fire
twice. In fact, there is an open issue about this: #1490 at the time of
writing this commit message.
We tried to only call the close function once by checking if those
events happen within the same "tick", which is not always the case...
Alright, let's ignore that issue for a second, there is another issue
that popped up... If you have a Dialog that is scrollable (because it is
greater than the current viewport) then a wild scrollbar appears (what a
weird Pokémon). The moment you try to click the scrollbar or drag it the
Dialog closes. What in the world...?
Well... turns out that `pointerdown` gets fired if you happen to "click"
(or touch) on the scrollbar. A click event does not get fired. No
worries we can fix this! Maybe...
(Narrator: ... nope ...)
One thing we can try is to measure the scrollbar width, and if you
happen to click near the edge then we ignore this click. You can think
of it like `let safeArea = viewportWidth - scrollBarWidth`. Everything
works great now! Maybe...
Well, let me tell you about macOS and "floating" scrollbars... you can't
measure those... AAAAAAAARGHHHH
Alright, scratch that, let's add an invisible 20px gap all around the
viewport without measuring as a safe area. Nobody will click in the 20px
gap, right, right?! Everything works great now! Maybe...
Mobile devices, yep, Dialogs are used there as well and usually there is
not a lot of room around those Dialogs so you almost always hit the
"safe area". Should we now try and detect the device people are
using...?
/me takes a deep breath...
Inhales... Exhales...
Alright, time to start thinking again... The outside click with a
"simple" click worked on Menu and Listbox not on the Dialog so this
should be enough right?
WAIT A MINUTE
Remember this piece of code from earlier:
```js
onClick(event) {
event.stopPropagation()
}
```
The click event never ever reaches the `window` so we can't detect the
click outside...
Let's move that code to the `Dialog.Panel` instead of on the `Dialog`
itself, this will make sure that we stop the click event from leaking
if you happen to nest a Dialog in a form and have a submitable
button/input in the `Dialog.Panel`. But if you click outside of the
`Dialog.Panel` the "click" event will bubble to the `window` so that we
can detect a click and check whether it was outside or not.
Time to start cleaning:
- ☑️ Remove all the scrollbar measuring code...
- Closing works on mobile now, no more safe area hack
- ☑️ Remove the pointerdown & mousedown event
- Outside click doesn't fire twice anymore
- ☑️ Use a "simple" click event listener
- We can click the scrollbar and the browser ignores it for us
All issues have been fixed! (Until the next one of course...)
* ensure a `Dialog.Panel` exists
* cleanup unnecessary code
* use capture phase for outside click behaviour
* further improve outside click
We added event.preventDefault() & event.defaultPrevented checks to make
sure that we only handle 1 layer at a time.
E.g.:
```js
<Dialog>
<Menu>
<Menu.Button>Button</Menu.Button>
<Menu.Items>...</Menu.Items>
</Menu>
</Dialog>
```
If you open the Dialog, then open the Menu, pressing `Escape` will close
the Menu but not the Dialog, pressing `Escape` again will close the
Dialog.
Now this is also applied to the outside click behaviour.
If you open the Dialog, then open the Menu, clicking outside will close
the Menu but not the Dialog, outside again will close the Dialog.
* add explicit `enabled` value to the `useOutsideClick` hook
* ensure outside click properly works with Poratl components
Usually this works out of the box, however our Portal components will
render inside the Dialog component "root" to ensure that it is inside
the non-inert tree and is inside the Dialog visually.
This means that the Portal is not in a separate container and
technically outside of the `Dialog.Panel` which means that it will close
when you click on a non-interactive item inside that Portal...
This fixes that and allows all Portal components.
* update changelog
* fix `slot` state of `RadioGroup` component
The `useEvent` is 1 tick too late (due to the update of the callback
happening in useEffect). This isn't a problem for event listeners, but
it is for functions that need to run "now".
We can change the `useLatestValue` hook to do something like:
```diff
export function useLatestValue<T>(value: T) {
let cache = useRef(value)
- useIsoMorphicEffect(() => {
- cache.current = value
- }, [value])
+ cache.current = value
return cache
}
```
But then we are mutating our refs in render which isn't ideal.
* update changelog
* add test to verify that the correct slot data is exposed
We had an issue where an open Dialog got hidden by css didn't properly
unmount because the Transition never "finished". We fixed this by
checking if the node was hidden by using `getBoundingClientRect`.
Today I learned that just *reading* those values (aka call
`node.getBoundingClientRect()`) it for whatever reason completely stops
the transition. This causes the enter transitions to completely stop
working.
Instead, we move this code so that we only check the existence of the
Node when we try to transition out because this means that the Node is
definitely there, just have to check its bounding rect.
* sort React imports
* improve type signature of the `useEvent` hook
* use more correct `useIsoMorphicEffect` check in `useEvent`
* refactor `useCallback` to cleaner `useEvent`
* convert `const` to `let`
Just for consistency..
* cleanup `Tabs` code
Created explicit functions that can be called from child components
instead of calling `dispatch` directly. Introduced a `useData` and
`useActions` hook to make child components easier.
The seperation of `useData` allows us to pass down props directly
instead of going via the `useReducer` hook and dispatching actions to
make values up to date.
* cleanup `Combobox` code
* cleanup `RadioGroup` code
* refactor `VisuallyHidden` to `Hidden` component
This new component will also make sure that it is visually hidden to
sighted users. However, it contains a few more features that are going
to be useful in other places as well. These features include:
1. Make visually hidden to sighted users (default)
2. Hide from assistive technology via `features={Features.Hidden}`
(will add `display: none;`)
3. Hide from assistive technology but make the element focusable via
`features={Features.Focusable}` (will add `aria-hidden="true"`)
* add `useEvent` hook
This will behave the same (roughly) as the new to be released `useEvent`
hook in React 18.X
This hook allows you to have a stable function that can "see" the latest
data it is using. We already had this concept using:
```js
let handleX = useLatestValue(() => {
// ...
})
```
But this returned a stable ref so you had to call `handleX.current()`.
This new hook is a bit nicer to work with but doesn't change much in the
end.
* add `useTabDirection` hook
This keeps track of the direction people are tabbing in. This returns a
ref so no re-renders happen because of this hook.
* add `useWatch` hook
This is similar to the `useEffect` hook, but only executes if values are
_actually_ changing... 😒
* add `microTask` util
* refactor `useFocusTrap` hook to `FocusTrap` component
Using a component directly allows us to simplify the focus trap logic
itself. Instead of intercepting the <kbd>Tab</kbd> keydown event and
figuring out the correct element to focus, we will now add 2 "guard"
buttons (hence why we require a component now). These buttons will
receive focus and if they do, redirect the focus to the first/last
element inside the focus trap.
The sweet part is that all the tabs in between those buttons will now be
handled natively by the browser. No need to find the first non disabled,
non hidden with correct tabIndex element!
* refactor the `Dialog` component to use the `FocusTrap` component
Also added a hidden button so that we know the correct "main" tree of
the application. Before this we were assuming the previous active
element which will still be correct in most cases but we don't have
access to that anymore since the logic is encapsulated inside the
FocusTrap component.
* ensure `<Portal />` properly cleans up
We make sure that the Portal is cleaning up its `element` properly.
We also make sure to call the `target.appendChild(element)`
conditionally because I ran into a super annoying bug where a focused
element got blurred because I believe that this re-mounts the element
instead of 'moving' it or just ignoring it, if it already is in the
correct spot.
* refactor: use `useEvent` instead of `useLatestValue`
Not really necessary, just cleaner.
* update changelog
* 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>
* ignore "outside click" on removed elements
Co-authored-by: Colin King <me@colinking.co>
* update changelog
Co-authored-by: Colin King <me@colinking.co>
* add tests to verify that tabbing around when using `initialFocus` works
* add nesting example to `playground-vue`
* fix nested dialog and initialFocus cycling
* make React dialog consistent
- Disable FocusLock on leaf Dialog's
* update changelog