@rific/drawer 0.2.0 → 0.3.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,44 @@
1
1
  import { Pressable } from '@rific/haptic-press'
2
- import { ComponentType, ReactNode, useEffect, useState } from 'react'
2
+ import { ReactNode, useEffect, useState } from 'react'
3
3
  import { LayoutChangeEvent, Platform, StyleProp, StyleSheet, View, ViewStyle } from 'react-native'
4
4
  import { Gesture, GestureDetector } from 'react-native-gesture-handler'
5
5
  import { useTheme } from 'react-native-paper'
6
6
  import Animated, { runOnJS, SharedValue, useAnimatedStyle, useSharedValue, withSpring, withTiming } from 'react-native-reanimated'
7
7
 
8
- import { type DrawerSide, getClosedOffset, getOpenDirection, isVerticalSide } from './geometry'
8
+ import { getDrawerConfig } from './DrawerConfig'
9
+ import { type DrawerDimension, type DrawerSide, getOpenDirection, isVerticalSide } from './geometry'
10
+ import { useDrawerSize } from './useDrawerSize'
9
11
 
10
- const SPRING = { damping: 40, stiffness: 300, overshootClamping: true }
12
+ // stiffness raised from 300 (was ~400-450ms to visually settle): at this damping the system is
13
+ // already overdamped (zeta = damping / (2*sqrt(stiffness)) >= 1), and Reanimated's spring stepper
14
+ // only uses `stiffness` (via omega0 = sqrt(stiffness/mass)) to drive the trajectory once zeta>=1;
15
+ // `damping` past the critical value (2*sqrt(stiffness)) only picks which internal branch runs, it
16
+ // doesn't slow the motion further. damping raised alongside it to stay at that critical value
17
+ // (2*sqrt(500) ≈ 44.7) rather than drift further overdamped, which would eat back some of the
18
+ // speedup. restDisplacementThreshold/restSpeedThreshold widened from Reanimated's defaults
19
+ // (0.01px / 2px/s): a threshold that tight makes the animation's own "finished" signal (which
20
+ // fires onOpened/onClosed below) lag well behind the point it's already visually indistinguishable
21
+ // from settled.
22
+ const SPRING = { damping: 45, stiffness: 500, overshootClamping: true, restDisplacementThreshold: 0.5, restSpeedThreshold: 10 }
11
23
  const VELOCITY_THRESHOLD = 500
12
24
 
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
- })()
25
+ // @rific/auto-paper is an optional peer, configured via configureDrawer()/<DrawerProvider>.
26
+ // When absent, the panel falls back to a solid fill.
28
27
 
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.
28
+ // useBlur is a hook and must be called unconditionally on every render (rules of hooks); this
29
+ // fallback stands in when auto-paper isn't configured, so a per-render branch isn't needed.
31
30
  const useBlurFallback = (override?: boolean) => override ?? false
32
- const useBlurHook = AutoPaper?.useBlur ?? useBlurFallback
33
31
 
34
32
  export type DrawerProps = {
35
33
  // 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.
34
+ // before): 0 renders no dimming at all, letting whatever's behind the panel stay fully visible.
37
35
  // Independent of blockingBackdrop: a panel can stay undimmed and still block touches, or vice versa.
38
36
  backdropOpacity?: number
39
37
  // Backdrop still dims/blurs identically either way; this only controls whether it intercepts
40
38
  // touches. false lets siblings behind/around the panel stay reachable while open.
41
39
  blockingBackdrop?: boolean
42
40
  blur?: boolean
43
- // Renders edge-to-edge behind the status bar/notch/home indicator, deliberately — pad your own
41
+ // Renders edge-to-edge behind the status bar/notch/home indicator, deliberately: pad your own
44
42
  // content with useSafeAreaInsets() (or a safe-area-aware header like @rific/scroll-view's) rather
45
43
  // than have this component impose a strategy that might double up with one you're already using.
46
44
  children?: ReactNode
@@ -48,67 +46,96 @@ export type DrawerProps = {
48
46
  // the fixed height/width below, and animates smoothly as that natural size changes. height/width
49
47
  // remain the pre-measurement placeholder (used until the first layout is measured).
50
48
  contentSize?: boolean
51
- // Renders a drag handle that can be swiped to close the panel, independent of the backdrop.
49
+ // Renders a drag handle that can be swiped to close the panel, independent of the backdrop. The
50
+ // handle floats just outside the panel's own bounds (over the backdrop, past the panel's
51
+ // content-facing edge) rather than claiming space inside it.
52
52
  dismissible?: boolean
53
- height?: number
53
+ // Shrinks the basis a *percentage* height/width/maxHeight/maxWidth resolves against, so `'100%'`
54
+ // fills exactly up to `edgeInset` px short of the screen's edge instead of reaching it — e.g.
55
+ // `edgeInset={insets.top}` on a `bottom` sheet with `maxHeight: '100%'` stops it just short of the
56
+ // status bar/notch, rather than sliding behind it. The geometry-clamp alternative to padding
57
+ // `content` away from a safe-area inset (see the README's Safe area section): the panel itself
58
+ // never reaches the inset, so there's nothing inside `content` to compensate for — don't combine
59
+ // the two for the same edge, or the inset ends up applied twice. Has no effect on a plain px
60
+ // number: that's taken as the exact size you asked for, same as always, letting you opt back out
61
+ // of the inset for a specific drawer by passing a literal value instead of a percentage. Defaults
62
+ // to 0 (no effect, today's behavior).
63
+ edgeInset?: number
64
+ height?: DrawerDimension
65
+ // Caps how far a drag on the handle can expand the panel past `height`, turning it into an
66
+ // expandable sheet: `open` still rests at `height`, with the remainder revealed by dragging the
67
+ // handle further open, up to this size (a bottom sheet opening to `height="50%"`,
68
+ // `maxHeight="100%"` rests at half the screen but can be pulled open the rest of the way).
69
+ // Defaults to `height` itself (no expansion). Percentage strings resolve against the window
70
+ // height, same as `height`. No effect when `contentSize` is true, whose box size already tracks
71
+ // content instead.
72
+ maxHeight?: DrawerDimension
73
+ // The maxWidth mirror of maxHeight, for `left`/`right` drawers.
74
+ maxWidth?: DrawerDimension
54
75
  onClose: () => void
55
- // Fires once the close animation actually finishes settling at closedOffset — not when `open`
76
+ // Fires once the close animation actually finishes settling at closedOffset, not when `open`
56
77
  // 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
78
+ // has visually finished sliding away. Lets a parent (e.g. DrawerInstanceProvider's isVisible) track "still
58
79
  // on screen, mid-outro" as distinct from "asked to close," for anything that needs to stay above
59
80
  // the panel for the full duration it's visible rather than disappearing the moment closing starts.
60
81
  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).
82
+ // Fires whenever the content wrapper's natural size is (re)measured: lets a parent (e.g.
83
+ // DrawerInstanceProvider) mirror the live size for its own math (DrawerEdgeSwipe's commit threshold).
63
84
  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),
85
+ // Fires once the open animation actually finishes settling at 0, the open-direction mirror of
86
+ // onClosed above. Not consumed internally by DrawerInstanceProvider (isVisible only needs the outro side),
66
87
  // but useful for anything that should wait until the panel has visually finished sliding in, e.g.
67
88
  // autofocusing a field inside `content` only once it's actually on screen.
68
89
  onOpened?: () => void
69
90
  open: boolean
70
91
  side?: DrawerSide
71
- // Whether the handle strip's own visual pill graphic draws — independent of `dismissible`, which
92
+ // Whether the handle strip's own visual pill graphic draws, independent of `dismissible`, which
72
93
  // controls the strip (and its drag-to-dismiss gesture) as a whole. false keeps the strip's hit area
73
94
  // (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-
95
+ // no way to hide the strip's *gesture* while keeping the pill visible: an invisible-but-still-
75
96
  // grabbable strip would be a hidden trap for stray touches, not a real use case.
76
97
  showHandle?: boolean
77
98
  translateOffset?: SharedValue<number>
78
- width?: number
99
+ width?: DrawerDimension
79
100
  // Stacking tier for this panel's backdrop/panel/handle, for apps that may have more than one Drawer
80
101
  // 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
102
+ // render/mount order, which for nested DrawerInstanceProviders is fixed by however they happen to be
103
+ // declared/nested, not necessarily the order that makes sense on screen. The backdrop uses this
83
104
  // value directly; the panel and its drag handle use zIndex + 1 / + 2, preserving their relative
84
105
  // order within the panel itself. Give a simultaneously-open drawer that should stack on top a
85
106
  // higher value than the one(s) underneath it.
86
107
  zIndex?: number
87
108
  }
88
109
 
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) => {
110
+ 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
111
  const { colors } = useTheme()
91
112
  const vertical = isVerticalSide(side)
92
- const size = vertical ? height : width
93
113
  const openDirection = getOpenDirection(side)
94
114
  const closeDirection = -openDirection as 1 | -1
95
115
 
96
116
  const [measuredSize, setMeasuredSize] = useState<number | null>(null)
97
- const effectiveSize = contentSize ? (measuredSize ?? size) : size
117
+ // contentSize measures its own box from natural content size, so it has no separate rest-vs-max
118
+ // concept: maxHeight/maxWidth (the drag-to-expand ceiling) only apply in the fixed-size path.
119
+ // height/width remain the pre-measurement placeholder until the first layout, same as before.
120
+ const sizeInput = contentSize ? (measuredSize ?? (vertical ? height : width)) : vertical ? height : width
121
+ const maxSizeInput = contentSize ? undefined : vertical ? maxHeight : maxWidth
122
+ const { closedOffset, effectiveSize, maxEffectiveSize, restOffset } = useDrawerSize(side, sizeInput, maxSizeInput, edgeInset)
98
123
 
99
- const closedOffset = getClosedOffset(side, effectiveSize)
100
124
  const internalTranslateOffset = useSharedValue(closedOffset)
101
125
  const translateOffset = externalTranslateOffset ?? internalTranslateOffset
102
- const resolvedBlur = useBlurHook(blur)
126
+ const { autoPaper } = getDrawerConfig()
127
+ const resolvedBlur = (autoPaper?.useBlur ?? useBlurFallback)(blur)
103
128
 
104
129
  // 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
130
+ // sizing only). Kept as a shared value (like translateOffset) rather than driven inline inside
106
131
  // useAnimatedStyle, so it only restarts its transition when effectiveSize actually changes.
107
132
  const animatedSize = useSharedValue(effectiveSize)
108
133
 
109
134
  useEffect(() => {
110
135
  if (open) {
111
- translateOffset.value = withSpring(0, SPRING, (finished) => {
136
+ // Rests at restOffset (== 0, fully expanded, when there's no maxHeight/maxWidth — identical
137
+ // to before), not always 0: an expandable sheet opens to its rest size, not its max size.
138
+ translateOffset.value = withSpring(restOffset, SPRING, (finished) => {
112
139
  if (finished && onOpened) runOnJS(onOpened)()
113
140
  })
114
141
  return
@@ -116,10 +143,10 @@ export const Drawer = ({ backdropOpacity = 0.45, blockingBackdrop = true, blur,
116
143
  translateOffset.value = withSpring(closedOffset, SPRING, (finished) => {
117
144
  if (finished && onClosed) runOnJS(onClosed)()
118
145
  })
119
- // onOpened/onClosed deliberately excluded — both are plain closures (DrawerProvider passes a
146
+ // onOpened/onClosed deliberately excluded: both are plain closures (DrawerInstanceProvider passes a
120
147
  // fresh function every render), and including them would restart this spring from its current
121
148
  // position every time the parent re-renders for any unrelated reason.
122
- }, [open, closedOffset, translateOffset])
149
+ }, [open, closedOffset, restOffset, translateOffset])
123
150
 
124
151
  useEffect(() => {
125
152
  if (contentSize) {
@@ -128,11 +155,22 @@ export const Drawer = ({ backdropOpacity = 0.45, blockingBackdrop = true, blur,
128
155
  }, [contentSize, effectiveSize, animatedSize])
129
156
 
130
157
  const drawerStyle = useAnimatedStyle(() => ({ transform: [vertical ? { translateY: translateOffset.value } : { translateX: translateOffset.value }] }))
131
- const backdropStyle = useAnimatedStyle(() => ({ opacity: (1 - Math.abs(translateOffset.value) / effectiveSize) * backdropOpacity }))
158
+ // Denominator is maxEffectiveSize, not effectiveSize/rest: dims proportionally to how much of the
159
+ // panel's full (possibly-expanded) size is currently covering the screen, not just its rest size —
160
+ // otherwise a still-collapsing expandable sheet would hit full backdropOpacity well before it's
161
+ // actually fully open. Reduces to today's exact behavior when there's no maxHeight/maxWidth, since
162
+ // maxEffectiveSize === effectiveSize then.
163
+ // Guarded against a 0 denominator: with a percentage height/width, maxEffectiveSize is briefly 0
164
+ // on web before the window's real size is measured (e.g. during SSR/hydration), which would
165
+ // otherwise divide 0/0 into NaN and crash react-native-web's style layer. Falls back to fully
166
+ // transparent, matching "closed," since a not-yet-sized panel isn't meaningfully open yet either.
167
+ const backdropStyle = useAnimatedStyle(() => ({ opacity: maxEffectiveSize > 0 ? (1 - Math.abs(translateOffset.value) / maxEffectiveSize) * backdropOpacity : 0 }))
132
168
  const animatedSizeStyle = useAnimatedStyle(() => (vertical ? { height: animatedSize.value } : { width: animatedSize.value }))
133
169
 
134
170
  const positionStyle = side === 'left' ? styles.anchorLeft : side === 'right' ? styles.anchorRight : side === 'top' ? styles.anchorTop : styles.anchorBottom
135
- const sizeStyle = vertical ? { height } : { width }
171
+ // maxEffectiveSize, not the raw height/width prop: the box must be big enough to show the panel
172
+ // fully expanded, even though it usually only shows effectiveSize px of that at rest.
173
+ const sizeStyle = vertical ? { height: maxEffectiveSize } : { width: maxEffectiveSize }
136
174
 
137
175
  const handleLayout = (event: LayoutChangeEvent) => {
138
176
  const measured = vertical ? event.nativeEvent.layout.height : event.nativeEvent.layout.width
@@ -143,25 +181,25 @@ export const Drawer = ({ backdropOpacity = 0.45, blockingBackdrop = true, blur,
143
181
  // contentSize=false: the inner wrapper fills the outer's fixed bounds exactly as before (untouched
144
182
  // path). contentSize=true: the background and the content-measuring wrapper have to be two separate
145
183
  // 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
184
+ // bounds: using absoluteFill on it would stretch it to match the outer, making onLayout report the
147
185
  // container's current size back to itself instead of the content's true size. But the outer's clip
148
186
  // window only catches up to a new size gradually (see the animatedSize effect above), so on any
149
187
  // 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
188
+ // of the outer leaves a gap below it: whatever's behind the drawer shows through until the outer
151
189
  // 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
190
+ // current (possibly mid-animation) size, and only the wrapper is sized/measured naturally, the same
153
191
  // structure as a CSS accordion expand/collapse either way.
154
192
  const fillStyle: StyleProp<ViewStyle> = StyleSheet.absoluteFill
155
193
 
156
194
  const fill =
157
- resolvedBlur && AutoPaper?.BlurView ? (
195
+ resolvedBlur && autoPaper ? (
158
196
  contentSize ? (
159
197
  <>
160
- <AutoPaper.BlurView style={fillStyle} />
198
+ <autoPaper.BlurView style={fillStyle} />
161
199
  <View onLayout={handleLayout}>{children}</View>
162
200
  </>
163
201
  ) : (
164
- <AutoPaper.BlurView style={fillStyle}>{children}</AutoPaper.BlurView>
202
+ <autoPaper.BlurView style={fillStyle}>{children}</autoPaper.BlurView>
165
203
  )
166
204
  ) : contentSize ? (
167
205
  <>
@@ -172,66 +210,157 @@ export const Drawer = ({ backdropOpacity = 0.45, blockingBackdrop = true, blur,
172
210
  <View style={[fillStyle, { backgroundColor: colors.surface }]}>{children}</View>
173
211
  )
174
212
 
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 }]
213
+ // Deliberately NOT clipped (no overflow: hidden here, unlike the contentSize clip wrapper below):
214
+ // the handle strip is a child of this view, positioned outside its bounds (see
215
+ // handleStripEdgeStyle), and must not be cut off by it.
216
+ // No explicit StyleProp<ViewStyle> annotation (react-native's own type, unaware of reanimated):
217
+ // drawerStyle/animatedSizeStyle come from useAnimatedStyle, which under reanimated 4.x's types
218
+ // returns an opaque AnimatedStyleHandle rather than a plain style object. Left uninferred, this
219
+ // is checked structurally against Animated.View's own `style` prop below, whose type (reanimated's
220
+ // AnimatedStyle<ViewStyle>) already accounts for that handle.
221
+ const drawerOuterStyle = contentSize ? [styles.drawer, positionStyle, drawerStyle, animatedSizeStyle, { zIndex: zIndex + 1 }] : [styles.drawer, positionStyle, sizeStyle, drawerStyle, { zIndex: zIndex + 1 }]
222
+ // contentSize's clip (overflow: hidden) + flex axis, previously on drawerOuterStyle itself, now
223
+ // live on this inner wrapper instead, so the outer stays unclipped for the handle strip's sake.
224
+ const contentClipStyle: StyleProp<ViewStyle> = [fillStyle, styles.clip, { flexDirection: vertical ? 'column' : 'row' }]
176
225
 
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`.
226
+ // Dismiss-and-expand handle: a strip pinned to the edge closest to the closed direction (the edge
227
+ // the panel slides back toward), gesture-matched to `side` the same way DrawerEdgeSwipe is. With no
228
+ // maxHeight/maxWidth it's a simple two-point toggle, same as before: starts from the OPEN/rest
229
+ // position (restOffset, which equals 0 in that case) and commits toward `closedOffset` or springs
230
+ // back. With one, it's three points along the same axis — closedOffset, restOffset, and fully
231
+ // expanded (0) — and the drag can commit toward whichever of those neighbors it's currently
232
+ // nearest, in either direction. Deliberately its own hit area rather than the whole panel, so it
233
+ // can't steal touches from arbitrary interactive content inside `children`.
182
234
  const clampMin = Math.min(0, closedOffset)
183
235
  const clampMax = Math.max(0, closedOffset)
184
236
 
237
+ // A single signed offset (e.g. closeDirection * 10) only arms the gesture for drags past that
238
+ // threshold in ONE direction — exactly what the plain close-only case wants (dragging the "wrong"
239
+ // way, further into "already open," should fall through rather than eat the touch), but it means a
240
+ // drag toward expanding — the opposite direction — never activates the gesture at all. With no
241
+ // maxHeight/maxWidth (restOffset always 0) that's fine, since there's nothing to expand into: keep
242
+ // the single-direction threshold, unchanged from before. Once expansion is possible, the gesture
243
+ // needs to recognize BOTH directions, so it switches to a symmetric range instead.
185
244
  const handleAxisGesture = vertical
186
245
  ? Gesture.Pan()
187
- .activeOffsetY(closeDirection * 10)
246
+ .activeOffsetY(restOffset !== 0 ? [-10, 10] : closeDirection * 10)
188
247
  .failOffsetX([-15, 15])
189
248
  : Gesture.Pan()
190
- .activeOffsetX(closeDirection * 10)
249
+ .activeOffsetX(restOffset !== 0 ? [-10, 10] : closeDirection * 10)
191
250
  .failOffsetY([-15, 15])
192
251
 
252
+ // Snapshotted at the start of each drag rather than assumed to be 0/restOffset: a drag can begin
253
+ // mid-expansion (or even mid-spring, if a new touch interrupts one still settling), and onUpdate
254
+ // needs to offset from wherever the panel actually was, not always from rest.
255
+ const gestureStartOffset = useSharedValue(closedOffset)
256
+
193
257
  const handleGesture = handleAxisGesture
194
258
  .enabled(open)
259
+ .onStart(() => {
260
+ 'worklet'
261
+ gestureStartOffset.value = translateOffset.value
262
+ })
195
263
  .onUpdate((event) => {
196
264
  'worklet'
197
265
  const translation = vertical ? event.translationY : event.translationX
198
- translateOffset.value = Math.min(clampMax, Math.max(clampMin, translation))
266
+ translateOffset.value = Math.min(clampMax, Math.max(clampMin, gestureStartOffset.value + translation))
199
267
  })
200
268
  .onEnd((event) => {
201
269
  'worklet'
202
- const translation = vertical ? event.translationY : event.translationX
203
270
  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)()
271
+ // Everything below works in "closing-direction" units (closeDirection-normalized), where 0 is
272
+ // always fully expanded and larger is always closer to closed, regardless of `side`'s sign
273
+ // convention — the same trick the old single-segment formula used, just reused per segment.
274
+ const velocityD = velocity * closeDirection
275
+ const currentD = translateOffset.value * closeDirection
276
+ const restD = restOffset * closeDirection // 0 when there's no maxHeight/maxWidth
277
+ let target: number
278
+ let closing = false
279
+ if (currentD <= restD) {
280
+ // Between rest (this segment's "start," at progress 0) and fully expanded (its far end, at
281
+ // progress 1): traveled = restD - currentD, since currentD counts down from restD to 0 as
282
+ // the drag moves toward expanding. Same 1/3-traveled threshold as the rest/closed segment
283
+ // below, just scoped to this segment's own length and direction; a fast fling toward
284
+ // expanding (velocityD very negative — the opposite sign from the closing fling below) also
285
+ // commits, regardless of distance covered.
286
+ const progress = restD > 0 ? (restD - currentD) / restD : 1
287
+ target = progress > 1 / 3 || velocityD < -VELOCITY_THRESHOLD ? 0 : restOffset
208
288
  } else {
209
- translateOffset.value = withSpring(0, SPRING)
289
+ // Between rest and fully closed. Identical formula (and, with no maxHeight/maxWidth, identical
290
+ // numbers) to the pre-expansion version of this gesture: restD is 0 and this segment's own
291
+ // length is effectiveSize, exactly like `effectiveSize` was the sole threshold denominator
292
+ // before. Guarded the same way as the expand branch above, for the same reason (see
293
+ // backdropStyle's comment): effectiveSize can be transiently 0 on web pre-hydration.
294
+ const progress = effectiveSize > 0 ? (currentD - restD) / effectiveSize : 1
295
+ closing = progress > 1 / 3 || velocityD > VELOCITY_THRESHOLD
296
+ target = closing ? closedOffset : restOffset
210
297
  }
298
+ translateOffset.value = withSpring(target, SPRING)
299
+ if (closing) runOnJS(onClose)()
211
300
  })
212
301
 
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.
302
+ // The whole strip along the closed-direction edge is grabbable, flush against it, not just the
303
+ // small pill drawn inside it, so there's nothing precise to aim for. It spans the full length of
304
+ // that edge (the panel's full height for left/right, full width for top/bottom), same as the
305
+ // panel itself, so it's reachable from anywhere along the edge, not just near the visible pill.
217
306
  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 }
307
+ // The strip's actual grabbable box extends HANDLE_HIT_SLOP further into the panel, past its own
308
+ // visual thickness, for a comfortable finger target (28 + 20 = 48px, matching Material Design's
309
+ // minimum touch target) without the pill itself growing or the strip visually eating panel space.
310
+ // Deliberately not done via Gesture.Pan().hitSlop(): react-native-gesture-handler's web backend
311
+ // binds its pointer listeners directly to the strip's own DOM node, so a pointer genuinely outside
312
+ // that node's rendered box never reaches the handler there at all — hitSlop only helps on native,
313
+ // where the OS extends the touch region a different way. Growing the real box, below, works
314
+ // everywhere a pointer/touch can actually land.
315
+ const HANDLE_HIT_SLOP = 20
316
+ const HANDLE_STRIP_TOTAL_THICKNESS = HANDLE_STRIP_THICKNESS + HANDLE_HIT_SLOP
317
+ const handleStripSizeStyle: ViewStyle = vertical ? { height: HANDLE_STRIP_TOTAL_THICKNESS, left: 0, right: 0 } : { bottom: 0, top: 0, width: HANDLE_STRIP_TOTAL_THICKNESS }
318
+ // Sits OUTSIDE the panel's own box rather than claiming interior visual space. Anchored from the
319
+ // FAR (backdrop-facing) edge — the opposite side from `side` — since that edge's distance from the
320
+ // panel is the one constant here (always exactly HANDLE_STRIP_THICKNESS past the panel, same as
321
+ // before this box grew): [oppositeSide]: -HANDLE_STRIP_THICKNESS fixes it there, and the box's full
322
+ // HANDLE_STRIP_TOTAL_THICKNESS width/height extends back from that fixed point, covering the
323
+ // original strip's footprint plus HANDLE_HIT_SLOP more, into the panel. `right`/`left`/`top`/
324
+ // `bottom` values are always relative to the parent's actual current edge, so — like the old
325
+ // percentage-based version — this still tracks correctly while contentSize is animating the
326
+ // panel's size. Requires drawerOuterStyle to stay unclipped (see its comment above) or this would
327
+ // be cut off.
328
+ const oppositeSide = side === 'left' ? 'right' : side === 'right' ? 'left' : side === 'top' ? 'bottom' : 'top'
329
+ const handleStripEdgeStyle: ViewStyle = { [oppositeSide]: -HANDLE_STRIP_THICKNESS }
330
+ // React Native sizes width/height as the outer box (unlike default web CSS box-sizing), so this
331
+ // padding — on the panel-facing side only — shrinks just the flex CONTENT area back down to the
332
+ // original 28px, without changing the box's own outer bounds. alignItems/justifyContent below then
333
+ // center the pill within that content area, landing it at exactly its pre-hit-slop spot: only the
334
+ // invisible margin around it grew.
335
+ 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
336
  const handlePillStyle: ViewStyle = vertical ? { height: 6, width: 64 } : { height: 64, width: 6 }
221
337
  // react-native-web reads `cursor` straight off style; native ignores the unknown key. ViewStyle (the
222
338
  // native type these files are typed against) has no such property, hence the cast.
223
339
  const webCursorStyle = { cursor: Platform.OS === 'web' ? 'pointer' : undefined } as ViewStyle
224
340
 
341
+ // The strip floats outside the panel's own box (see handleStripEdgeStyle above), so unlike the
342
+ // panel's own content, it isn't carried off-screen by the panel's close translation: that
343
+ // translation is only ever calibrated to hide the panel's own maxEffectiveSize, not the strip's
344
+ // extra thickness beyond it. Once less than the strip's own thickness of panel remains visible,
345
+ // there's no panel edge left for it to be flush against, so it's hidden — otherwise it wells up
346
+ // sitting right at the screen edge looking like the drawer is still (a little) open, even at rest
347
+ // fully closed. visibleSize mirrors the gesture's own D-space trick above: 0 at fully closed,
348
+ // maxEffectiveSize at fully expanded, regardless of `side`'s sign convention.
349
+ const handleVisibilityStyle = useAnimatedStyle(() => {
350
+ const visibleSize = maxEffectiveSize - translateOffset.value * closeDirection
351
+ return { opacity: visibleSize >= HANDLE_STRIP_THICKNESS ? 1 : 0 }
352
+ })
353
+
225
354
  return (
226
355
  <>
227
356
  <Animated.View style={[styles.backdrop, { zIndex }, backdropStyle]} pointerEvents={open && blockingBackdrop ? 'auto' : 'none'}>
228
357
  <Pressable style={StyleSheet.absoluteFill} onPress={onClose} />
229
358
  </Animated.View>
230
359
  <Animated.View style={drawerOuterStyle}>
231
- {fill}
360
+ {contentSize ? <View style={contentClipStyle}>{fill}</View> : fill}
232
361
  {dismissible && (
233
362
  <GestureDetector gesture={handleGesture}>
234
- <View style={[styles.handleStrip, handleStripSizeStyle, handleStripEdgeStyle, webCursorStyle, { zIndex: zIndex + 2 }]}>{showHandle && <View style={[styles.handlePill, handlePillStyle, { backgroundColor: colors.onSurfaceVariant }]} />}</View>
363
+ <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
364
  </GestureDetector>
236
365
  )}
237
366
  </Animated.View>
@@ -275,8 +404,7 @@ const styles = StyleSheet.create({
275
404
  position: 'absolute'
276
405
  },
277
406
  handlePill: {
278
- borderRadius: 3,
279
- opacity: 0.5
407
+ borderRadius: 3
280
408
  },
281
409
  handleStrip: {
282
410
  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
+ }
@@ -2,25 +2,38 @@ import { StyleSheet, View } from 'react-native'
2
2
  import { Gesture, GestureDetector } from 'react-native-gesture-handler'
3
3
  import { runOnJS, SharedValue, withSpring } from 'react-native-reanimated'
4
4
 
5
- import { type DrawerSide, getClosedOffset, getOpenDirection, isVerticalSide } from './geometry'
5
+ import { type DrawerDimension, type DrawerSide, getOpenDirection, isVerticalSide } from './geometry'
6
+ import { useDrawerSize } from './useDrawerSize'
6
7
 
7
8
  const EDGE_WIDTH = 24
8
- const SPRING = { damping: 40, overshootClamping: true, stiffness: 300 }
9
+ // Kept identical to Drawer.tsx's own SPRING (see its comment for the reasoning) so an
10
+ // edge-swipe-opened drawer settles at the same rate as a tap-opened one.
11
+ const SPRING = { damping: 45, overshootClamping: true, stiffness: 500, restDisplacementThreshold: 0.5, restSpeedThreshold: 10 }
9
12
  const VELOCITY_THRESHOLD = 500
10
13
 
11
14
  export type DrawerEdgeSwipeProps = {
15
+ // Mirrors Drawer's own edgeInset: keep both in sync (same value) so this gesture's clamp/rest
16
+ // math agrees with the panel it's driving. See Drawer's own doc comment for the full rationale
17
+ // (in short: shrinks the basis a *percentage* height/maxHeight/width/maxWidth resolves against; a
18
+ // literal px number is unaffected).
19
+ edgeInset?: number
12
20
  enabled?: boolean
13
- height?: number
21
+ height?: DrawerDimension
22
+ // Mirrors Drawer's own maxHeight: when set, an edge swipe still only opens to `height` (the rest
23
+ // size), not all the way to this ceiling — matching Drawer's tap-to-open behavior, which also
24
+ // lands at rest. Reaching past rest, up to maxHeight, is only ever done via Drawer's own handle.
25
+ maxHeight?: DrawerDimension
26
+ // The maxWidth mirror of maxHeight, for `left`/`right` drawers.
27
+ maxWidth?: DrawerDimension
14
28
  onOpen: () => void
15
29
  side?: DrawerSide
16
30
  translateOffset: SharedValue<number>
17
- width?: number
31
+ width?: DrawerDimension
18
32
  }
19
33
 
20
- export const DrawerEdgeSwipe = ({ enabled = true, height = 300, onOpen, side = 'left', translateOffset, width = 300 }: DrawerEdgeSwipeProps) => {
34
+ export const DrawerEdgeSwipe = ({ edgeInset = 0, enabled = true, height = 300, maxHeight, maxWidth, onOpen, side = 'left', translateOffset, width = 300 }: DrawerEdgeSwipeProps) => {
21
35
  const vertical = isVerticalSide(side)
22
- const size = vertical ? height : width
23
- const closedOffset = getClosedOffset(side, size)
36
+ const { closedOffset, effectiveSize, restOffset } = useDrawerSize(side, vertical ? height : width, vertical ? maxHeight : maxWidth, edgeInset)
24
37
  const openDirection = getOpenDirection(side)
25
38
  const clampMin = Math.min(0, closedOffset)
26
39
  const clampMax = Math.max(0, closedOffset)
@@ -44,9 +57,9 @@ export const DrawerEdgeSwipe = ({ enabled = true, height = 300, onOpen, side = '
44
57
  'worklet'
45
58
  const translation = vertical ? event.translationY : event.translationX
46
59
  const velocity = vertical ? event.velocityY : event.velocityX
47
- const commit = translation * openDirection > size / 3 || velocity * openDirection > VELOCITY_THRESHOLD
60
+ const commit = translation * openDirection > effectiveSize / 3 || velocity * openDirection > VELOCITY_THRESHOLD
48
61
  if (commit) {
49
- translateOffset.value = withSpring(0, SPRING)
62
+ translateOffset.value = withSpring(restOffset, SPRING)
50
63
  runOnJS(onOpen)()
51
64
  } else {
52
65
  translateOffset.value = withSpring(closedOffset, SPRING)