emilkowalski / vaul

A drawer component for React.
https://vaul.emilkowal.ski
MIT License
6.46k stars 215 forks source link

Fix: Ensure drawer opens at the specified active snap point on initial render #473

Closed KhalafAbdi closed 1 month ago

KhalafAbdi commented 1 month ago

Issue: Drawer Initializes at First Snap Point Regardless of activeSnapPoint Setting

When setting activeSnapPointto any value other than the first element in the snapPointsarray, the drawer component always initializes at the first snap point on the initial render. It only updates to the correct activeSnapPointafter an external re-render occurs. This behavior is due to how the initial style is assigned and how snapPointsOffsetis calculated when the component first mounts.

This can be recreated by running the repo localy, and try to use /initial-snap test route. This does not work of the bat (it will open drawer with offset for the first element in the snapPointsarray), but opening initial-snap/page.tsx, and saving any change, will force a re-render which will then open the drawer at the correct snap point.

Current Behavior:

The DialogPrimitive.Content component assigns the CSS custom property --snap-point-height to snapPointsOffset[0], which corresponds to the first snap point.

https://github.com/emilkowalski/vaul/blob/1142f66e22f65c74d6f8a0068df1dfa809f1c356/src/index.tsx#L885-L892

Proposed Change in PR:

In this PR, I changed the initialization of --snap-point-height to use activeSnapPointIndexinstead of always defaulting to the first element. This ensures that the drawer starts at the correct snap point specified by activeSnapPointwithout requiring a re-render.