@rific/drawer 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/Drawer.tsx CHANGED
@@ -1,46 +1,43 @@
1
- import { Pressable } from '@rific/haptic-press'
2
- import { ComponentType, ReactNode, useEffect, useState } from 'react'
1
+ import { ReactNode, useEffect, useRef, useState } from 'react'
3
2
  import { LayoutChangeEvent, Platform, StyleProp, StyleSheet, View, ViewStyle } from 'react-native'
4
3
  import { Gesture, GestureDetector } from 'react-native-gesture-handler'
5
4
  import { useTheme } from 'react-native-paper'
6
5
  import Animated, { runOnJS, SharedValue, useAnimatedStyle, useSharedValue, withSpring, withTiming } from 'react-native-reanimated'
7
6
 
8
- import { type DrawerSide, getClosedOffset, getOpenDirection, isVerticalSide } from './geometry'
7
+ import { getDrawerConfig } from './DrawerConfig'
8
+ import { type DrawerDimension, type DrawerSide, getOpenDirection, isVerticalSide } from './geometry'
9
+ import { useDrawerSize } from './useDrawerSize'
9
10
 
10
- const SPRING = { damping: 40, stiffness: 300, overshootClamping: true }
11
+ // stiffness raised from 300 (was ~400-450ms to visually settle): at this damping the system is
12
+ // already overdamped (zeta = damping / (2*sqrt(stiffness)) >= 1), and Reanimated's spring stepper
13
+ // only uses `stiffness` (via omega0 = sqrt(stiffness/mass)) to drive the trajectory once zeta>=1;
14
+ // `damping` past the critical value (2*sqrt(stiffness)) only picks which internal branch runs, it
15
+ // doesn't slow the motion further. damping raised alongside it to stay at that critical value
16
+ // (2*sqrt(500) ≈ 44.7) rather than drift further overdamped, which would eat back some of the
17
+ // speedup. restDisplacementThreshold/restSpeedThreshold widened from Reanimated's defaults
18
+ // (0.01px / 2px/s): a threshold that tight makes the animation's own "finished" signal (which
19
+ // fires onOpened/onClosed below) lag well behind the point it's already visually indistinguishable
20
+ // from settled.
21
+ const SPRING = { damping: 45, stiffness: 500, overshootClamping: true, restDisplacementThreshold: 0.5, restSpeedThreshold: 10 }
11
22
  const VELOCITY_THRESHOLD = 500
12
23
 
13
- // Minimal local shape of @rific/auto-paper covering only the members used below — avoids forcing
14
- // TypeScript to resolve the optional peer's real types for consumers who never installed it.
15
- interface AutoPaperModule {
16
- BlurView: ComponentType<{ children?: ReactNode; onLayout?: (event: LayoutChangeEvent) => void; style?: StyleProp<ViewStyle> }>
17
- useBlur: (override?: boolean) => boolean
18
- }
19
-
20
- // @rific/auto-paper is an optional peer — when absent, the panel falls back to a solid fill.
21
- const AutoPaper = (() => {
22
- try {
23
- return require('@rific/auto-paper') as AutoPaperModule
24
- } catch {
25
- return null
26
- }
27
- })()
24
+ // @rific/auto-paper is an optional peer, configured via configureDrawer()/<DrawerProvider>.
25
+ // When absent, the panel falls back to a solid fill.
28
26
 
29
- // useBlur is a hook and must be called unconditionally on every render (rules of hooks) — this
30
- // fallback stands in when @rific/auto-paper isn't installed, so a per-render branch isn't needed.
27
+ // useBlur is a hook and must be called unconditionally on every render (rules of hooks); this
28
+ // fallback stands in when auto-paper isn't configured, so a per-render branch isn't needed.
31
29
  const useBlurFallback = (override?: boolean) => override ?? false
32
- const useBlurHook = AutoPaper?.useBlur ?? useBlurFallback
33
30
 
34
31
  export type DrawerProps = {
35
32
  // Peak backdrop opacity once fully open (scaled down as the panel slides toward closed, same as
36
- // before) — 0 renders no dimming at all, letting whatever's behind the panel stay fully visible.
33
+ // before): 0 renders no dimming at all, letting whatever's behind the panel stay fully visible.
37
34
  // Independent of blockingBackdrop: a panel can stay undimmed and still block touches, or vice versa.
38
35
  backdropOpacity?: number
39
36
  // Backdrop still dims/blurs identically either way; this only controls whether it intercepts
40
37
  // touches. false lets siblings behind/around the panel stay reachable while open.
41
38
  blockingBackdrop?: boolean
42
39
  blur?: boolean
43
- // Renders edge-to-edge behind the status bar/notch/home indicator, deliberately — pad your own
40
+ // Renders edge-to-edge behind the status bar/notch/home indicator, deliberately: pad your own
44
41
  // content with useSafeAreaInsets() (or a safe-area-aware header like @rific/scroll-view's) rather
45
42
  // than have this component impose a strategy that might double up with one you're already using.
46
43
  children?: ReactNode
@@ -48,67 +45,100 @@ export type DrawerProps = {
48
45
  // the fixed height/width below, and animates smoothly as that natural size changes. height/width
49
46
  // remain the pre-measurement placeholder (used until the first layout is measured).
50
47
  contentSize?: boolean
51
- // Renders a drag handle that can be swiped to close the panel, independent of the backdrop.
48
+ // Renders a drag handle that can be swiped to close the panel, independent of the backdrop. The
49
+ // handle floats just outside the panel's own bounds (over the backdrop, past the panel's
50
+ // content-facing edge) rather than claiming space inside it.
52
51
  dismissible?: boolean
53
- height?: number
52
+ // Shrinks the basis a *percentage* height/width/maxHeight/maxWidth resolves against, so `'100%'`
53
+ // fills exactly up to `edgeInset` px short of the screen's edge instead of reaching it — e.g.
54
+ // `edgeInset={insets.top}` on a `bottom` sheet with `maxHeight: '100%'` stops it just short of the
55
+ // status bar/notch, rather than sliding behind it. The geometry-clamp alternative to padding
56
+ // `content` away from a safe-area inset (see the README's Safe area section): the panel itself
57
+ // never reaches the inset, so there's nothing inside `content` to compensate for — don't combine
58
+ // the two for the same edge, or the inset ends up applied twice. Has no effect on a plain px
59
+ // number: that's taken as the exact size you asked for, same as always, letting you opt back out
60
+ // of the inset for a specific drawer by passing a literal value instead of a percentage. Defaults
61
+ // to 0 (no effect, today's behavior).
62
+ edgeInset?: number
63
+ height?: DrawerDimension
64
+ // Caps how far a drag on the handle can expand the panel past `height`, turning it into an
65
+ // expandable sheet: `open` still rests at `height`, with the remainder revealed by dragging the
66
+ // handle further open, up to this size (a bottom sheet opening to `height="50%"`,
67
+ // `maxHeight="100%"` rests at half the screen but can be pulled open the rest of the way).
68
+ // Defaults to `height` itself (no expansion). Percentage strings resolve against the window
69
+ // height, same as `height`. No effect when `contentSize` is true, whose box size already tracks
70
+ // content instead.
71
+ maxHeight?: DrawerDimension
72
+ // The maxWidth mirror of maxHeight, for `left`/`right` drawers.
73
+ maxWidth?: DrawerDimension
54
74
  onClose: () => void
55
- // Fires once the close animation actually finishes settling at closedOffset — not when `open`
75
+ // Fires once the close animation actually finishes settling at closedOffset, not when `open`
56
76
  // merely flips to false, which happens the instant something asks to close, well before the panel
57
- // has visually finished sliding away. Lets a parent (e.g. DrawerProvider's isVisible) track "still
77
+ // has visually finished sliding away. Lets a parent (e.g. DrawerInstanceProvider's isVisible) track "still
58
78
  // on screen, mid-outro" as distinct from "asked to close," for anything that needs to stay above
59
79
  // the panel for the full duration it's visible rather than disappearing the moment closing starts.
60
80
  onClosed?: () => void
61
- // Fires whenever the content wrapper's natural size is (re)measured — lets a parent (e.g.
62
- // DrawerProvider) mirror the live size for its own math (DrawerEdgeSwipe's commit threshold).
81
+ // Fires whenever the content wrapper's natural size is (re)measured: lets a parent (e.g.
82
+ // DrawerInstanceProvider) mirror the live size for its own math (DrawerEdgeSwipe's commit threshold).
63
83
  onMeasure?: (size: number) => void
64
- // Fires once the open animation actually finishes settling at 0 — the open-direction mirror of
65
- // onClosed above. Not consumed internally by DrawerProvider (isVisible only needs the outro side),
84
+ // Fires once the open animation actually finishes settling at 0, the open-direction mirror of
85
+ // onClosed above. Not consumed internally by DrawerInstanceProvider (isVisible only needs the outro side),
66
86
  // but useful for anything that should wait until the panel has visually finished sliding in, e.g.
67
87
  // autofocusing a field inside `content` only once it's actually on screen.
68
88
  onOpened?: () => void
69
89
  open: boolean
70
90
  side?: DrawerSide
71
- // Whether the handle strip's own visual pill graphic draws — independent of `dismissible`, which
91
+ // Whether the handle strip's own visual pill graphic draws, independent of `dismissible`, which
72
92
  // controls the strip (and its drag-to-dismiss gesture) as a whole. false keeps the strip's hit area
73
93
  // (and the gesture attached to it) exactly as before; only the pill itself stops rendering. There's
74
- // no way to hide the strip's *gesture* while keeping the pill visible — an invisible-but-still-
94
+ // no way to hide the strip's *gesture* while keeping the pill visible: an invisible-but-still-
75
95
  // grabbable strip would be a hidden trap for stray touches, not a real use case.
76
96
  showHandle?: boolean
77
97
  translateOffset?: SharedValue<number>
78
- width?: number
98
+ width?: DrawerDimension
79
99
  // Stacking tier for this panel's backdrop/panel/handle, for apps that may have more than one Drawer
80
100
  // open at once (e.g. two separate createDrawer() instances). Plain View z-index ties break on
81
- // render/mount order, which for nested DrawerProviders is fixed by however they happen to be
82
- // declared/nested — not necessarily the order that makes sense on screen. The backdrop uses this
101
+ // render/mount order, which for nested DrawerInstanceProviders is fixed by however they happen to be
102
+ // declared/nested, not necessarily the order that makes sense on screen. The backdrop uses this
83
103
  // value directly; the panel and its drag handle use zIndex + 1 / + 2, preserving their relative
84
104
  // order within the panel itself. Give a simultaneously-open drawer that should stack on top a
85
105
  // higher value than the one(s) underneath it.
86
106
  zIndex?: number
87
107
  }
88
108
 
89
- export const Drawer = ({ backdropOpacity = 0.45, blockingBackdrop = true, blur, children, contentSize = false, dismissible = true, height = 300, onClose, onClosed, onMeasure, onOpened, open, side = 'left', showHandle = true, translateOffset: externalTranslateOffset, width = 300, zIndex = 50 }: DrawerProps) => {
109
+ export const Drawer = ({ backdropOpacity = 0.45, blockingBackdrop = true, blur, children, contentSize = false, dismissible = true, edgeInset = 0, height = 300, maxHeight, maxWidth, onClose, onClosed, onMeasure, onOpened, open, side = 'left', showHandle = true, translateOffset: externalTranslateOffset, width = 300, zIndex = 50 }: DrawerProps) => {
90
110
  const { colors } = useTheme()
91
111
  const vertical = isVerticalSide(side)
92
- const size = vertical ? height : width
93
112
  const openDirection = getOpenDirection(side)
94
113
  const closeDirection = -openDirection as 1 | -1
95
114
 
96
115
  const [measuredSize, setMeasuredSize] = useState<number | null>(null)
97
- const effectiveSize = contentSize ? (measuredSize ?? size) : size
116
+ // Tracks the last value actually committed to measuredSize, rounded — see handleLayout below for
117
+ // why the comparison has to happen against this rather than just re-deriving it from measuredSize
118
+ // itself on every call.
119
+ const lastMeasuredRef = useRef<number | null>(null)
120
+ // contentSize measures its own box from natural content size, so it has no separate rest-vs-max
121
+ // concept: maxHeight/maxWidth (the drag-to-expand ceiling) only apply in the fixed-size path.
122
+ // height/width remain the pre-measurement placeholder until the first layout, same as before.
123
+ const sizeInput = contentSize ? (measuredSize ?? (vertical ? height : width)) : vertical ? height : width
124
+ const maxSizeInput = contentSize ? undefined : vertical ? maxHeight : maxWidth
125
+ const { closedOffset, effectiveSize, maxEffectiveSize, restOffset } = useDrawerSize(side, sizeInput, maxSizeInput, edgeInset)
98
126
 
99
- const closedOffset = getClosedOffset(side, effectiveSize)
100
127
  const internalTranslateOffset = useSharedValue(closedOffset)
101
128
  const translateOffset = externalTranslateOffset ?? internalTranslateOffset
102
- const resolvedBlur = useBlurHook(blur)
129
+ const { autoPaper } = getDrawerConfig()
130
+ const resolvedBlur = (autoPaper?.useBlur ?? useBlurFallback)(blur)
103
131
 
104
132
  // The container's own animated size, eased toward effectiveSize whenever it changes (content-driven
105
- // sizing only). Kept as a shared value — like translateOffset — rather than driven inline inside
133
+ // sizing only). Kept as a shared value (like translateOffset) rather than driven inline inside
106
134
  // useAnimatedStyle, so it only restarts its transition when effectiveSize actually changes.
107
135
  const animatedSize = useSharedValue(effectiveSize)
108
136
 
109
137
  useEffect(() => {
110
138
  if (open) {
111
- translateOffset.value = withSpring(0, SPRING, (finished) => {
139
+ // Rests at restOffset (== 0, fully expanded, when there's no maxHeight/maxWidth — identical
140
+ // to before), not always 0: an expandable sheet opens to its rest size, not its max size.
141
+ translateOffset.value = withSpring(restOffset, SPRING, (finished) => {
112
142
  if (finished && onOpened) runOnJS(onOpened)()
113
143
  })
114
144
  return
@@ -116,10 +146,10 @@ export const Drawer = ({ backdropOpacity = 0.45, blockingBackdrop = true, blur,
116
146
  translateOffset.value = withSpring(closedOffset, SPRING, (finished) => {
117
147
  if (finished && onClosed) runOnJS(onClosed)()
118
148
  })
119
- // onOpened/onClosed deliberately excluded — both are plain closures (DrawerProvider passes a
149
+ // onOpened/onClosed deliberately excluded: both are plain closures (DrawerInstanceProvider passes a
120
150
  // fresh function every render), and including them would restart this spring from its current
121
151
  // position every time the parent re-renders for any unrelated reason.
122
- }, [open, closedOffset, translateOffset])
152
+ }, [open, closedOffset, restOffset, translateOffset])
123
153
 
124
154
  useEffect(() => {
125
155
  if (contentSize) {
@@ -128,14 +158,39 @@ export const Drawer = ({ backdropOpacity = 0.45, blockingBackdrop = true, blur,
128
158
  }, [contentSize, effectiveSize, animatedSize])
129
159
 
130
160
  const drawerStyle = useAnimatedStyle(() => ({ transform: [vertical ? { translateY: translateOffset.value } : { translateX: translateOffset.value }] }))
131
- const backdropStyle = useAnimatedStyle(() => ({ opacity: (1 - Math.abs(translateOffset.value) / effectiveSize) * backdropOpacity }))
161
+ // Denominator is maxEffectiveSize, not effectiveSize/rest: dims proportionally to how much of the
162
+ // panel's full (possibly-expanded) size is currently covering the screen, not just its rest size —
163
+ // otherwise a still-collapsing expandable sheet would hit full backdropOpacity well before it's
164
+ // actually fully open. Reduces to today's exact behavior when there's no maxHeight/maxWidth, since
165
+ // maxEffectiveSize === effectiveSize then.
166
+ // Guarded against a 0 denominator: with a percentage height/width, maxEffectiveSize is briefly 0
167
+ // on web before the window's real size is measured (e.g. during SSR/hydration), which would
168
+ // otherwise divide 0/0 into NaN and crash react-native-web's style layer. Falls back to fully
169
+ // transparent, matching "closed," since a not-yet-sized panel isn't meaningfully open yet either.
170
+ const backdropStyle = useAnimatedStyle(() => ({ opacity: maxEffectiveSize > 0 ? (1 - Math.abs(translateOffset.value) / maxEffectiveSize) * backdropOpacity : 0 }))
132
171
  const animatedSizeStyle = useAnimatedStyle(() => (vertical ? { height: animatedSize.value } : { width: animatedSize.value }))
133
172
 
134
173
  const positionStyle = side === 'left' ? styles.anchorLeft : side === 'right' ? styles.anchorRight : side === 'top' ? styles.anchorTop : styles.anchorBottom
135
- const sizeStyle = vertical ? { height } : { width }
174
+ // maxEffectiveSize, not the raw height/width prop: the box must be big enough to show the panel
175
+ // fully expanded, even though it usually only shows effectiveSize px of that at rest.
176
+ const sizeStyle = vertical ? { height: maxEffectiveSize } : { width: maxEffectiveSize }
136
177
 
178
+ // Rounded (not the raw sub-pixel float layout reports) and short-circuited against the last value
179
+ // actually committed: an animated ancestor (animatedSizeStyle below, mid-withTiming) can cause
180
+ // Yoga to re-measure this supposedly content-unconstrained wrapper on every frame it's still
181
+ // moving, and floating-point noise between passes (e.g. 283.3333740234375 vs 283.33331298828125 —
182
+ // the same logical height, off by ~1/16000th of a pixel) is "different" by strict equality. Left
183
+ // unguarded, that noise commits a "new" measuredSize every frame, which restarts the very
184
+ // withTiming animation that's causing the re-measurement in the first place — a self-sustaining
185
+ // loop that never lets the height settle, seen as a stutter rather than a single smooth resize.
186
+ // Comparing against a ref (not measuredSize itself) matters here: measuredSize is the state that's
187
+ // deliberately being skipped on a no-op call, so re-deriving the comparison from it would still
188
+ // see the same (unchanged) value next time regardless — the ref is what actually remembers what
189
+ // was last committed.
137
190
  const handleLayout = (event: LayoutChangeEvent) => {
138
- const measured = vertical ? event.nativeEvent.layout.height : event.nativeEvent.layout.width
191
+ const measured = Math.round(vertical ? event.nativeEvent.layout.height : event.nativeEvent.layout.width)
192
+ if (lastMeasuredRef.current === measured) return
193
+ lastMeasuredRef.current = measured
139
194
  setMeasuredSize(measured)
140
195
  onMeasure?.(measured)
141
196
  }
@@ -143,25 +198,25 @@ export const Drawer = ({ backdropOpacity = 0.45, blockingBackdrop = true, blur,
143
198
  // contentSize=false: the inner wrapper fills the outer's fixed bounds exactly as before (untouched
144
199
  // path). contentSize=true: the background and the content-measuring wrapper have to be two separate
145
200
  // views. The wrapper must render at its OWN natural size, unconstrained by the outer's (animated)
146
- // bounds — using absoluteFill on it would stretch it to match the outer, making onLayout report the
201
+ // bounds: using absoluteFill on it would stretch it to match the outer, making onLayout report the
147
202
  // container's current size back to itself instead of the content's true size. But the outer's clip
148
203
  // window only catches up to a new size gradually (see the animatedSize effect above), so on any
149
204
  // frame where content is smaller than the still-large outer, a background sized to CONTENT instead
150
- // of the outer leaves a gap below it — whatever's behind the drawer shows through until the outer
205
+ // of the outer leaves a gap below it: whatever's behind the drawer shows through until the outer
151
206
  // finishes shrinking. So the background is its own absoluteFill sibling, always exactly the outer's
152
- // current (possibly mid-animation) size, and only the wrapper is sized/measured naturally — the same
207
+ // current (possibly mid-animation) size, and only the wrapper is sized/measured naturally, the same
153
208
  // structure as a CSS accordion expand/collapse either way.
154
209
  const fillStyle: StyleProp<ViewStyle> = StyleSheet.absoluteFill
155
210
 
156
211
  const fill =
157
- resolvedBlur && AutoPaper?.BlurView ? (
212
+ resolvedBlur && autoPaper ? (
158
213
  contentSize ? (
159
214
  <>
160
- <AutoPaper.BlurView style={fillStyle} />
215
+ <autoPaper.BlurView style={fillStyle} />
161
216
  <View onLayout={handleLayout}>{children}</View>
162
217
  </>
163
218
  ) : (
164
- <AutoPaper.BlurView style={fillStyle}>{children}</AutoPaper.BlurView>
219
+ <autoPaper.BlurView style={fillStyle}>{children}</autoPaper.BlurView>
165
220
  )
166
221
  ) : contentSize ? (
167
222
  <>
@@ -171,67 +226,195 @@ export const Drawer = ({ backdropOpacity = 0.45, blockingBackdrop = true, blur,
171
226
  ) : (
172
227
  <View style={[fillStyle, { backgroundColor: colors.surface }]}>{children}</View>
173
228
  )
229
+ // contentSize's measuring wrapper above is deliberately given no style of its own (see the
230
+ // comment above `fillStyle`): it must report ITS OWN natural size, which only works if `children`
231
+ // itself has an intrinsic height Yoga can compute directly from its subtree — e.g. plain
232
+ // Views/Text/FABs, including a `flexWrap: 'wrap'` row like FabRow. A `ScrollView` breaks this: on
233
+ // native, ScrollView's outer box does NOT size itself to its content the way a plain View does —
234
+ // it needs a bounded height from an ANCESTOR instead (see ScrollView's own docs) — so measuring
235
+ // one via onLayout here reports some small, real-but-wrong box height (whatever Yoga happens to
236
+ // resolve it to absent an explicit bound) rather than the content's true extent, and clips
237
+ // anything beyond that. contentSize's `children` must render its own natural-height content
238
+ // directly (no ScrollView) for this measurement to be meaningful.
174
239
 
175
- const drawerOuterStyle: StyleProp<ViewStyle> = contentSize ? [styles.drawer, positionStyle, styles.clip, { flexDirection: vertical ? 'column' : 'row' }, drawerStyle, animatedSizeStyle, { zIndex: zIndex + 1 }] : [styles.drawer, positionStyle, sizeStyle, drawerStyle, { zIndex: zIndex + 1 }]
240
+ // Deliberately NOT clipped (no overflow: hidden here, unlike the contentSize clip wrapper below):
241
+ // the handle strip is a child of this view, positioned outside its bounds (see
242
+ // handleStripEdgeStyle), and must not be cut off by it.
243
+ // No explicit StyleProp<ViewStyle> annotation (react-native's own type, unaware of reanimated):
244
+ // drawerStyle/animatedSizeStyle come from useAnimatedStyle, which under reanimated 4.x's types
245
+ // returns an opaque AnimatedStyleHandle rather than a plain style object. Left uninferred, this
246
+ // is checked structurally against Animated.View's own `style` prop below, whose type (reanimated's
247
+ // AnimatedStyle<ViewStyle>) already accounts for that handle.
248
+ const drawerOuterStyle = contentSize ? [styles.drawer, positionStyle, drawerStyle, animatedSizeStyle, { zIndex: zIndex + 1 }] : [styles.drawer, positionStyle, sizeStyle, drawerStyle, { zIndex: zIndex + 1 }]
249
+ // contentSize's clip (overflow: hidden) + flex axis, previously on drawerOuterStyle itself, now
250
+ // live on this inner wrapper instead, so the outer stays unclipped for the handle strip's sake.
251
+ const contentClipStyle: StyleProp<ViewStyle> = [fillStyle, styles.clip, { flexDirection: vertical ? 'column' : 'row' }]
176
252
 
177
- // Dismiss-by-drag handle: a strip pinned to the edge closest to the closed direction (the edge the
178
- // panel slides back toward), gesture-matched to `side` the same way DrawerEdgeSwipe is, just
179
- // mirrored — it starts from the OPEN position (0) and commits toward `closedOffset` instead of the
180
- // reverse. Deliberately its own hit area rather than the whole panel, so it can't steal touches from
181
- // arbitrary interactive content inside `children`.
253
+ // Dismiss-and-expand handle: a strip pinned to the edge closest to the closed direction (the edge
254
+ // the panel slides back toward), gesture-matched to `side` the same way DrawerEdgeSwipe is. With no
255
+ // maxHeight/maxWidth it's a simple two-point toggle, same as before: starts from the OPEN/rest
256
+ // position (restOffset, which equals 0 in that case) and commits toward `closedOffset` or springs
257
+ // back. With one, it's three points along the same axis — closedOffset, restOffset, and fully
258
+ // expanded (0) — and the drag can commit toward whichever of those neighbors it's currently
259
+ // nearest, in either direction. Deliberately its own hit area rather than the whole panel, so it
260
+ // can't steal touches from arbitrary interactive content inside `children`.
182
261
  const clampMin = Math.min(0, closedOffset)
183
262
  const clampMax = Math.max(0, closedOffset)
184
263
 
264
+ // A single signed offset (e.g. closeDirection * 10) only arms the gesture for drags past that
265
+ // threshold in ONE direction — exactly what the plain close-only case wants (dragging the "wrong"
266
+ // way, further into "already open," should fall through rather than eat the touch), but it means a
267
+ // drag toward expanding — the opposite direction — never activates the gesture at all. With no
268
+ // maxHeight/maxWidth (restOffset always 0) that's fine, since there's nothing to expand into: keep
269
+ // the single-direction threshold, unchanged from before. Once expansion is possible, the gesture
270
+ // needs to recognize BOTH directions, so it switches to a symmetric range instead.
185
271
  const handleAxisGesture = vertical
186
272
  ? Gesture.Pan()
187
- .activeOffsetY(closeDirection * 10)
273
+ .activeOffsetY(restOffset !== 0 ? [-10, 10] : closeDirection * 10)
188
274
  .failOffsetX([-15, 15])
189
275
  : Gesture.Pan()
190
- .activeOffsetX(closeDirection * 10)
276
+ .activeOffsetX(restOffset !== 0 ? [-10, 10] : closeDirection * 10)
191
277
  .failOffsetY([-15, 15])
192
278
 
279
+ // Snapshotted at the start of each drag rather than assumed to be 0/restOffset: a drag can begin
280
+ // mid-expansion (or even mid-spring, if a new touch interrupts one still settling), and onUpdate
281
+ // needs to offset from wherever the panel actually was, not always from rest.
282
+ const gestureStartOffset = useSharedValue(closedOffset)
283
+
284
+ // react-native-gesture-handler's own Tap, not @rific/haptic-press's plain-RN Pressable: this
285
+ // sits in the same GestureDetector-based system as the panel's own drag handle below, rather
286
+ // than mixing RNGH's native recognizers with RN's separate classic responder system on the one
287
+ // view in the tree (the backdrop) that most needs to reliably win a touch over whatever's behind
288
+ // it, including a consumer's own full-screen canvas gestures (e.g. Swirlio's pan/pinch/rotation).
289
+ const backdropTapGesture = Gesture.Tap()
290
+ .enabled(open && blockingBackdrop)
291
+ .onEnd((_event, success) => {
292
+ if (success) runOnJS(onClose)()
293
+ })
294
+
193
295
  const handleGesture = handleAxisGesture
194
296
  .enabled(open)
297
+ .onStart(() => {
298
+ 'worklet'
299
+ gestureStartOffset.value = translateOffset.value
300
+ })
195
301
  .onUpdate((event) => {
196
302
  'worklet'
197
303
  const translation = vertical ? event.translationY : event.translationX
198
- translateOffset.value = Math.min(clampMax, Math.max(clampMin, translation))
304
+ translateOffset.value = Math.min(clampMax, Math.max(clampMin, gestureStartOffset.value + translation))
199
305
  })
200
306
  .onEnd((event) => {
201
307
  'worklet'
202
- const translation = vertical ? event.translationY : event.translationX
203
308
  const velocity = vertical ? event.velocityY : event.velocityX
204
- const commit = translation * closeDirection > effectiveSize / 3 || velocity * closeDirection > VELOCITY_THRESHOLD
205
- if (commit) {
206
- translateOffset.value = withSpring(closedOffset, SPRING)
207
- runOnJS(onClose)()
309
+ // Everything below works in "closing-direction" units (closeDirection-normalized), where 0 is
310
+ // always fully expanded and larger is always closer to closed, regardless of `side`'s sign
311
+ // convention — the same trick the old single-segment formula used, just reused per segment.
312
+ const velocityD = velocity * closeDirection
313
+ const currentD = translateOffset.value * closeDirection
314
+ const restD = restOffset * closeDirection // 0 when there's no maxHeight/maxWidth
315
+ let target: number
316
+ let closing = false
317
+ if (currentD <= restD) {
318
+ // Between rest (this segment's "start," at progress 0) and fully expanded (its far end, at
319
+ // progress 1): traveled = restD - currentD, since currentD counts down from restD to 0 as
320
+ // the drag moves toward expanding. Same 1/3-traveled threshold as the rest/closed segment
321
+ // below, just scoped to this segment's own length and direction; a fast fling toward
322
+ // expanding (velocityD very negative — the opposite sign from the closing fling below) also
323
+ // commits, regardless of distance covered.
324
+ const progress = restD > 0 ? (restD - currentD) / restD : 1
325
+ target = progress > 1 / 3 || velocityD < -VELOCITY_THRESHOLD ? 0 : restOffset
208
326
  } else {
209
- translateOffset.value = withSpring(0, SPRING)
327
+ // Between rest and fully closed. Identical formula (and, with no maxHeight/maxWidth, identical
328
+ // numbers) to the pre-expansion version of this gesture: restD is 0 and this segment's own
329
+ // length is effectiveSize, exactly like `effectiveSize` was the sole threshold denominator
330
+ // before. Guarded the same way as the expand branch above, for the same reason (see
331
+ // backdropStyle's comment): effectiveSize can be transiently 0 on web pre-hydration.
332
+ const progress = effectiveSize > 0 ? (currentD - restD) / effectiveSize : 1
333
+ closing = progress > 1 / 3 || velocityD > VELOCITY_THRESHOLD
334
+ target = closing ? closedOffset : restOffset
210
335
  }
336
+ translateOffset.value = withSpring(target, SPRING)
337
+ if (closing) runOnJS(onClose)()
211
338
  })
212
339
 
213
- // The whole strip along the closed-direction edge is grabbable, flush against it — not just the
214
- // small pill drawn inside it — so there's nothing precise to aim for. The strip's own thickness
215
- // already reads as clearance from the rest of the panel's content, so there's no separate inset
216
- // spent on top of that for nothing.
340
+ // The whole strip along the closed-direction edge is grabbable, flush against it, not just the
341
+ // small pill drawn inside it, so there's nothing precise to aim for. It spans the full length of
342
+ // that edge (the panel's full height for left/right, full width for top/bottom), same as the
343
+ // panel itself, so it's reachable from anywhere along the edge, not just near the visible pill.
217
344
  const HANDLE_STRIP_THICKNESS = 28
218
- const handleStripSizeStyle: ViewStyle = vertical ? { height: HANDLE_STRIP_THICKNESS, left: 0, right: 0 } : { bottom: 0, top: 0, width: HANDLE_STRIP_THICKNESS }
219
- const handleStripEdgeStyle: ViewStyle = side === 'bottom' ? { top: 0 } : side === 'top' ? { bottom: 0 } : side === 'left' ? { right: 0 } : { left: 0 }
345
+ // The strip's actual grabbable box extends HANDLE_HIT_SLOP further into the panel, past its own
346
+ // visual thickness, for a comfortable finger target (28 + 20 = 48px, matching Material Design's
347
+ // minimum touch target) without the pill itself growing or the strip visually eating panel space.
348
+ // Deliberately not done via Gesture.Pan().hitSlop(): react-native-gesture-handler's web backend
349
+ // binds its pointer listeners directly to the strip's own DOM node, so a pointer genuinely outside
350
+ // that node's rendered box never reaches the handler there at all — hitSlop only helps on native,
351
+ // where the OS extends the touch region a different way. Growing the real box, below, works
352
+ // everywhere a pointer/touch can actually land.
353
+ const HANDLE_HIT_SLOP = 20
354
+ const HANDLE_STRIP_TOTAL_THICKNESS = HANDLE_STRIP_THICKNESS + HANDLE_HIT_SLOP
355
+ const handleStripSizeStyle: ViewStyle = vertical ? { height: HANDLE_STRIP_TOTAL_THICKNESS, left: 0, right: 0 } : { bottom: 0, top: 0, width: HANDLE_STRIP_TOTAL_THICKNESS }
356
+ // Sits OUTSIDE the panel's own box rather than claiming interior visual space. Anchored from the
357
+ // FAR (backdrop-facing) edge — the opposite side from `side` — since that edge's distance from the
358
+ // panel is the one constant here (always exactly HANDLE_STRIP_THICKNESS past the panel, same as
359
+ // before this box grew): [oppositeSide]: -HANDLE_STRIP_THICKNESS fixes it there, and the box's full
360
+ // HANDLE_STRIP_TOTAL_THICKNESS width/height extends back from that fixed point, covering the
361
+ // original strip's footprint plus HANDLE_HIT_SLOP more, into the panel. `right`/`left`/`top`/
362
+ // `bottom` values are always relative to the parent's actual current edge, so — like the old
363
+ // percentage-based version — this still tracks correctly while contentSize is animating the
364
+ // panel's size. Requires drawerOuterStyle to stay unclipped (see its comment above) or this would
365
+ // be cut off.
366
+ const oppositeSide = side === 'left' ? 'right' : side === 'right' ? 'left' : side === 'top' ? 'bottom' : 'top'
367
+ const handleStripEdgeStyle: ViewStyle = { [oppositeSide]: -HANDLE_STRIP_THICKNESS }
368
+ // React Native sizes width/height as the outer box (unlike default web CSS box-sizing), so this
369
+ // padding — on the panel-facing side only — shrinks just the flex CONTENT area back down to the
370
+ // original 28px, without changing the box's own outer bounds. alignItems/justifyContent below then
371
+ // center the pill within that content area, landing it at exactly its pre-hit-slop spot: only the
372
+ // invisible margin around it grew.
373
+ const handleStripPaddingStyle: ViewStyle = side === 'left' ? { paddingLeft: HANDLE_HIT_SLOP } : side === 'right' ? { paddingRight: HANDLE_HIT_SLOP } : side === 'top' ? { paddingTop: HANDLE_HIT_SLOP } : { paddingBottom: HANDLE_HIT_SLOP }
220
374
  const handlePillStyle: ViewStyle = vertical ? { height: 6, width: 64 } : { height: 64, width: 6 }
221
375
  // react-native-web reads `cursor` straight off style; native ignores the unknown key. ViewStyle (the
222
376
  // native type these files are typed against) has no such property, hence the cast.
223
377
  const webCursorStyle = { cursor: Platform.OS === 'web' ? 'pointer' : undefined } as ViewStyle
224
378
 
379
+ // The strip floats outside the panel's own box (see handleStripEdgeStyle above), so unlike the
380
+ // panel's own content, it isn't carried off-screen by the panel's close translation: that
381
+ // translation is only ever calibrated to hide the panel's own maxEffectiveSize, not the strip's
382
+ // extra thickness beyond it. Once less than the strip's own thickness of panel remains visible,
383
+ // there's no panel edge left for it to be flush against, so it's hidden — otherwise it wells up
384
+ // sitting right at the screen edge looking like the drawer is still (a little) open, even at rest
385
+ // fully closed. visibleSize mirrors the gesture's own D-space trick above: 0 at fully closed,
386
+ // maxEffectiveSize at fully expanded, regardless of `side`'s sign convention.
387
+ const handleVisibilityStyle = useAnimatedStyle(() => {
388
+ const visibleSize = maxEffectiveSize - translateOffset.value * closeDirection
389
+ return { opacity: visibleSize >= HANDLE_STRIP_THICKNESS ? 1 : 0 }
390
+ })
391
+
225
392
  return (
226
393
  <>
227
- <Animated.View style={[styles.backdrop, { zIndex }, backdropStyle]} pointerEvents={open && blockingBackdrop ? 'auto' : 'none'}>
228
- <Pressable style={StyleSheet.absoluteFill} onPress={onClose} />
394
+ <Animated.View style={[styles.backdropPosition, { zIndex, pointerEvents: open && blockingBackdrop ? 'auto' : 'none' }]}>
395
+ {/* The dimming tint is its own child, carrying the actual black backgroundColor and
396
+ backdropStyle's animated opacity, separate from the tap-catching view below and from the
397
+ OUTER container above (which must stay paint-free, not just visually transparent at
398
+ opacity 0): on iOS, a view at opacity 0 (e.g. backdropOpacity={0}, an intentional no-dim
399
+ backdrop — see controlGroups.tsx) is excluded from hit-testing entirely by UIKit,
400
+ regardless of pointerEvents. That's fine for a purely decorative tint, but it would
401
+ silently make the whole backdrop untouchable too if the SAME view carried both — and if
402
+ the outer container carried the background color instead, it would paint solid black at
403
+ full opacity at all times (no animated opacity of its own), open or not. */}
404
+ <Animated.View style={[styles.backdropTint, backdropStyle]} pointerEvents='none' />
405
+ <GestureDetector gesture={backdropTapGesture}>
406
+ {/* collapsable={false}: this view has no paint properties of its own (no background,
407
+ no animated style), exactly the shape React Native's view-flattening optimizer removes
408
+ from the native tree on native platforms — leaving the GestureDetector above with no real
409
+ view left to attach its tap recognizer to, so it would silently never receive a touch. */}
410
+ <Animated.View collapsable={false} style={StyleSheet.absoluteFill} />
411
+ </GestureDetector>
229
412
  </Animated.View>
230
413
  <Animated.View style={drawerOuterStyle}>
231
- {fill}
414
+ {contentSize ? <View style={contentClipStyle}>{fill}</View> : fill}
232
415
  {dismissible && (
233
416
  <GestureDetector gesture={handleGesture}>
234
- <View style={[styles.handleStrip, handleStripSizeStyle, handleStripEdgeStyle, webCursorStyle, { zIndex: zIndex + 2 }]}>{showHandle && <View style={[styles.handlePill, handlePillStyle, { backgroundColor: colors.onSurfaceVariant }]} />}</View>
417
+ <Animated.View style={[styles.handleStrip, handleStripSizeStyle, handleStripEdgeStyle, handleStripPaddingStyle, webCursorStyle, handleVisibilityStyle, { zIndex: zIndex + 2 }]}>{showHandle && <View style={[styles.handlePill, handlePillStyle, { backgroundColor: colors.surface }]} />}</Animated.View>
235
418
  </GestureDetector>
236
419
  )}
237
420
  </Animated.View>
@@ -260,7 +443,14 @@ const styles = StyleSheet.create({
260
443
  right: 0,
261
444
  top: 0
262
445
  },
263
- backdrop: {
446
+ backdropPosition: {
447
+ bottom: 0,
448
+ left: 0,
449
+ position: 'absolute',
450
+ right: 0,
451
+ top: 0
452
+ },
453
+ backdropTint: {
264
454
  backgroundColor: '#000',
265
455
  bottom: 0,
266
456
  left: 0,
@@ -275,8 +465,7 @@ const styles = StyleSheet.create({
275
465
  position: 'absolute'
276
466
  },
277
467
  handlePill: {
278
- borderRadius: 3,
279
- opacity: 0.5
468
+ borderRadius: 3
280
469
  },
281
470
  handleStrip: {
282
471
  alignItems: 'center',
@@ -0,0 +1,48 @@
1
+ import { type ComponentType, type ReactNode } from 'react'
2
+ import type { LayoutChangeEvent, StyleProp, ViewStyle } from 'react-native'
3
+
4
+ // Local mirror of @rific/auto-paper's exports, limited to what Drawer touches. Avoids
5
+ // forcing TypeScript to resolve the optional peer's real types for consumers who never
6
+ // installed it. @rific/auto-paper is never auto-detected: Metro doesn't rewrite a
7
+ // require()-in-try/catch call into its module graph inside an ESM (.mjs) build, so the
8
+ // module-level detection this package used to do silently broke as soon as consumers'
9
+ // bundlers resolved this package's ESM entry point.
10
+ export type AutoPaperModule = {
11
+ BlurView: ComponentType<{ children?: ReactNode; onLayout?: (event: LayoutChangeEvent) => void; style?: StyleProp<ViewStyle> }>
12
+ useBlur: (override?: boolean) => boolean
13
+ }
14
+
15
+ export type DrawerConfig = {
16
+ /** Injects @rific/auto-paper so Drawer's panel renders a real frosted-glass backdrop via BlurView/useBlur instead of its solid-fill fallback. Pass `import * as AutoPaper from '@rific/auto-paper'`; omit to keep the solid fallback. */
17
+ autoPaper?: AutoPaperModule
18
+ }
19
+
20
+ let config: DrawerConfig = {}
21
+
22
+ // Plain module-level config rather than React Context: this is one-time app setup ("does
23
+ // this app have @rific/auto-paper?"), not per-render reactive state, so a Provider that has
24
+ // to exist just to thread a value through the tree is more ceremony than the problem needs.
25
+ // Call this directly, or mount <DrawerProvider> once near your app root (it just calls this
26
+ // for you). Not reactive: calling it again after components have already rendered won't
27
+ // retroactively update them, fine for one-time startup config, not for runtime toggling.
28
+ //
29
+ // Not to be confused with the per-instance provider createDrawer() returns
30
+ // (DrawerInstanceProvider): this one is app-wide, mounted once, for optional peer config;
31
+ // that one is per-drawer, mounted once per createDrawer() call, for that drawer's own state.
32
+ export const configureDrawer = (next: DrawerConfig) => {
33
+ config = { ...config, ...next }
34
+ }
35
+
36
+ export const getDrawerConfig = (): DrawerConfig => config
37
+
38
+ export type DrawerProviderProps = DrawerConfig & { children: ReactNode }
39
+
40
+ // Thin wrapper around configureDrawer() for consumers who'd rather mount a Provider than call
41
+ // a setup function directly: every @rific package wires up the same way this way. Calls
42
+ // configureDrawer() synchronously during render (not in an effect), so the config is already
43
+ // set by the time any descendant <Drawer> renders. Effects run bottom-up after children have
44
+ // already rendered once, which would be one render too late here.
45
+ export const DrawerProvider = ({ autoPaper, children }: DrawerProviderProps) => {
46
+ configureDrawer({ autoPaper })
47
+ return <>{children}</>
48
+ }