@rific/drawer 0.1.2 → 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/README.md +131 -8
- package/dist/index.d.mts +80 -17
- package/dist/index.d.ts +80 -17
- package/dist/index.js +265 -57
- package/dist/index.mjs +266 -61
- package/package.json +21 -11
- package/src/Drawer.tsx +373 -27
- package/src/DrawerConfig.tsx +48 -0
- package/src/DrawerEdgeSwipe.tsx +57 -19
- package/src/createDrawer.tsx +149 -21
- package/src/geometry.ts +52 -0
- package/src/index.ts +3 -1
- package/src/useDrawerSize.ts +55 -0
package/src/Drawer.tsx
CHANGED
|
@@ -1,54 +1,393 @@
|
|
|
1
1
|
import { Pressable } from '@rific/haptic-press'
|
|
2
|
-
import { ReactNode, useEffect } from 'react'
|
|
3
|
-
import { StyleSheet } from 'react-native'
|
|
2
|
+
import { ReactNode, useEffect, useState } from 'react'
|
|
3
|
+
import { LayoutChangeEvent, Platform, StyleProp, StyleSheet, View, ViewStyle } from 'react-native'
|
|
4
|
+
import { Gesture, GestureDetector } from 'react-native-gesture-handler'
|
|
4
5
|
import { useTheme } from 'react-native-paper'
|
|
5
|
-
import Animated, { SharedValue, useAnimatedStyle, useSharedValue, withSpring } from 'react-native-reanimated'
|
|
6
|
+
import Animated, { runOnJS, SharedValue, useAnimatedStyle, useSharedValue, withSpring, withTiming } from 'react-native-reanimated'
|
|
6
7
|
|
|
7
|
-
|
|
8
|
+
import { getDrawerConfig } from './DrawerConfig'
|
|
9
|
+
import { type DrawerDimension, type DrawerSide, getOpenDirection, isVerticalSide } from './geometry'
|
|
10
|
+
import { useDrawerSize } from './useDrawerSize'
|
|
11
|
+
|
|
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 }
|
|
23
|
+
const VELOCITY_THRESHOLD = 500
|
|
24
|
+
|
|
25
|
+
// @rific/auto-paper is an optional peer, configured via configureDrawer()/<DrawerProvider>.
|
|
26
|
+
// When absent, the panel falls back to a solid fill.
|
|
27
|
+
|
|
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.
|
|
30
|
+
const useBlurFallback = (override?: boolean) => override ?? false
|
|
8
31
|
|
|
9
32
|
export type DrawerProps = {
|
|
10
|
-
//
|
|
33
|
+
// Peak backdrop opacity once fully open (scaled down as the panel slides toward closed, same as
|
|
34
|
+
// before): 0 renders no dimming at all, letting whatever's behind the panel stay fully visible.
|
|
35
|
+
// Independent of blockingBackdrop: a panel can stay undimmed and still block touches, or vice versa.
|
|
36
|
+
backdropOpacity?: number
|
|
37
|
+
// Backdrop still dims/blurs identically either way; this only controls whether it intercepts
|
|
38
|
+
// touches. false lets siblings behind/around the panel stay reachable while open.
|
|
39
|
+
blockingBackdrop?: boolean
|
|
40
|
+
blur?: boolean
|
|
41
|
+
// Renders edge-to-edge behind the status bar/notch/home indicator, deliberately: pad your own
|
|
11
42
|
// content with useSafeAreaInsets() (or a safe-area-aware header like @rific/scroll-view's) rather
|
|
12
43
|
// than have this component impose a strategy that might double up with one you're already using.
|
|
13
44
|
children?: ReactNode
|
|
45
|
+
// When true, the panel sizes itself to its content's natural size along the main axis instead of
|
|
46
|
+
// the fixed height/width below, and animates smoothly as that natural size changes. height/width
|
|
47
|
+
// remain the pre-measurement placeholder (used until the first layout is measured).
|
|
48
|
+
contentSize?: boolean
|
|
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
|
+
dismissible?: boolean
|
|
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
|
|
14
75
|
onClose: () => void
|
|
76
|
+
// Fires once the close animation actually finishes settling at closedOffset, not when `open`
|
|
77
|
+
// merely flips to false, which happens the instant something asks to close, well before the panel
|
|
78
|
+
// has visually finished sliding away. Lets a parent (e.g. DrawerInstanceProvider's isVisible) track "still
|
|
79
|
+
// on screen, mid-outro" as distinct from "asked to close," for anything that needs to stay above
|
|
80
|
+
// the panel for the full duration it's visible rather than disappearing the moment closing starts.
|
|
81
|
+
onClosed?: () => void
|
|
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).
|
|
84
|
+
onMeasure?: (size: number) => void
|
|
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),
|
|
87
|
+
// but useful for anything that should wait until the panel has visually finished sliding in, e.g.
|
|
88
|
+
// autofocusing a field inside `content` only once it's actually on screen.
|
|
89
|
+
onOpened?: () => void
|
|
15
90
|
open: boolean
|
|
16
|
-
side?:
|
|
17
|
-
|
|
18
|
-
|
|
91
|
+
side?: DrawerSide
|
|
92
|
+
// Whether the handle strip's own visual pill graphic draws, independent of `dismissible`, which
|
|
93
|
+
// controls the strip (and its drag-to-dismiss gesture) as a whole. false keeps the strip's hit area
|
|
94
|
+
// (and the gesture attached to it) exactly as before; only the pill itself stops rendering. There's
|
|
95
|
+
// no way to hide the strip's *gesture* while keeping the pill visible: an invisible-but-still-
|
|
96
|
+
// grabbable strip would be a hidden trap for stray touches, not a real use case.
|
|
97
|
+
showHandle?: boolean
|
|
98
|
+
translateOffset?: SharedValue<number>
|
|
99
|
+
width?: DrawerDimension
|
|
100
|
+
// Stacking tier for this panel's backdrop/panel/handle, for apps that may have more than one Drawer
|
|
101
|
+
// open at once (e.g. two separate createDrawer() instances). Plain View z-index ties break on
|
|
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
|
|
104
|
+
// value directly; the panel and its drag handle use zIndex + 1 / + 2, preserving their relative
|
|
105
|
+
// order within the panel itself. Give a simultaneously-open drawer that should stack on top a
|
|
106
|
+
// higher value than the one(s) underneath it.
|
|
107
|
+
zIndex?: number
|
|
19
108
|
}
|
|
20
109
|
|
|
21
|
-
export const Drawer = ({ children, onClose, open, side = 'left',
|
|
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) => {
|
|
22
111
|
const { colors } = useTheme()
|
|
23
|
-
const
|
|
24
|
-
const
|
|
25
|
-
const
|
|
112
|
+
const vertical = isVerticalSide(side)
|
|
113
|
+
const openDirection = getOpenDirection(side)
|
|
114
|
+
const closeDirection = -openDirection as 1 | -1
|
|
115
|
+
|
|
116
|
+
const [measuredSize, setMeasuredSize] = useState<number | null>(null)
|
|
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)
|
|
123
|
+
|
|
124
|
+
const internalTranslateOffset = useSharedValue(closedOffset)
|
|
125
|
+
const translateOffset = externalTranslateOffset ?? internalTranslateOffset
|
|
126
|
+
const { autoPaper } = getDrawerConfig()
|
|
127
|
+
const resolvedBlur = (autoPaper?.useBlur ?? useBlurFallback)(blur)
|
|
128
|
+
|
|
129
|
+
// The container's own animated size, eased toward effectiveSize whenever it changes (content-driven
|
|
130
|
+
// sizing only). Kept as a shared value (like translateOffset) rather than driven inline inside
|
|
131
|
+
// useAnimatedStyle, so it only restarts its transition when effectiveSize actually changes.
|
|
132
|
+
const animatedSize = useSharedValue(effectiveSize)
|
|
133
|
+
|
|
134
|
+
useEffect(() => {
|
|
135
|
+
if (open) {
|
|
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) => {
|
|
139
|
+
if (finished && onOpened) runOnJS(onOpened)()
|
|
140
|
+
})
|
|
141
|
+
return
|
|
142
|
+
}
|
|
143
|
+
translateOffset.value = withSpring(closedOffset, SPRING, (finished) => {
|
|
144
|
+
if (finished && onClosed) runOnJS(onClosed)()
|
|
145
|
+
})
|
|
146
|
+
// onOpened/onClosed deliberately excluded: both are plain closures (DrawerInstanceProvider passes a
|
|
147
|
+
// fresh function every render), and including them would restart this spring from its current
|
|
148
|
+
// position every time the parent re-renders for any unrelated reason.
|
|
149
|
+
}, [open, closedOffset, restOffset, translateOffset])
|
|
26
150
|
|
|
27
151
|
useEffect(() => {
|
|
28
|
-
|
|
29
|
-
|
|
152
|
+
if (contentSize) {
|
|
153
|
+
animatedSize.value = withTiming(effectiveSize)
|
|
154
|
+
}
|
|
155
|
+
}, [contentSize, effectiveSize, animatedSize])
|
|
156
|
+
|
|
157
|
+
const drawerStyle = useAnimatedStyle(() => ({ transform: [vertical ? { translateY: translateOffset.value } : { translateX: translateOffset.value }] }))
|
|
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 }))
|
|
168
|
+
const animatedSizeStyle = useAnimatedStyle(() => (vertical ? { height: animatedSize.value } : { width: animatedSize.value }))
|
|
169
|
+
|
|
170
|
+
const positionStyle = side === 'left' ? styles.anchorLeft : side === 'right' ? styles.anchorRight : side === 'top' ? styles.anchorTop : styles.anchorBottom
|
|
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 }
|
|
174
|
+
|
|
175
|
+
const handleLayout = (event: LayoutChangeEvent) => {
|
|
176
|
+
const measured = vertical ? event.nativeEvent.layout.height : event.nativeEvent.layout.width
|
|
177
|
+
setMeasuredSize(measured)
|
|
178
|
+
onMeasure?.(measured)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// contentSize=false: the inner wrapper fills the outer's fixed bounds exactly as before (untouched
|
|
182
|
+
// path). contentSize=true: the background and the content-measuring wrapper have to be two separate
|
|
183
|
+
// views. The wrapper must render at its OWN natural size, unconstrained by the outer's (animated)
|
|
184
|
+
// bounds: using absoluteFill on it would stretch it to match the outer, making onLayout report the
|
|
185
|
+
// container's current size back to itself instead of the content's true size. But the outer's clip
|
|
186
|
+
// window only catches up to a new size gradually (see the animatedSize effect above), so on any
|
|
187
|
+
// frame where content is smaller than the still-large outer, a background sized to CONTENT instead
|
|
188
|
+
// of the outer leaves a gap below it: whatever's behind the drawer shows through until the outer
|
|
189
|
+
// finishes shrinking. So the background is its own absoluteFill sibling, always exactly the outer's
|
|
190
|
+
// current (possibly mid-animation) size, and only the wrapper is sized/measured naturally, the same
|
|
191
|
+
// structure as a CSS accordion expand/collapse either way.
|
|
192
|
+
const fillStyle: StyleProp<ViewStyle> = StyleSheet.absoluteFill
|
|
193
|
+
|
|
194
|
+
const fill =
|
|
195
|
+
resolvedBlur && autoPaper ? (
|
|
196
|
+
contentSize ? (
|
|
197
|
+
<>
|
|
198
|
+
<autoPaper.BlurView style={fillStyle} />
|
|
199
|
+
<View onLayout={handleLayout}>{children}</View>
|
|
200
|
+
</>
|
|
201
|
+
) : (
|
|
202
|
+
<autoPaper.BlurView style={fillStyle}>{children}</autoPaper.BlurView>
|
|
203
|
+
)
|
|
204
|
+
) : contentSize ? (
|
|
205
|
+
<>
|
|
206
|
+
<View style={[fillStyle, { backgroundColor: colors.surface }]} />
|
|
207
|
+
<View onLayout={handleLayout}>{children}</View>
|
|
208
|
+
</>
|
|
209
|
+
) : (
|
|
210
|
+
<View style={[fillStyle, { backgroundColor: colors.surface }]}>{children}</View>
|
|
211
|
+
)
|
|
212
|
+
|
|
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' }]
|
|
225
|
+
|
|
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`.
|
|
234
|
+
const clampMin = Math.min(0, closedOffset)
|
|
235
|
+
const clampMax = Math.max(0, closedOffset)
|
|
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.
|
|
244
|
+
const handleAxisGesture = vertical
|
|
245
|
+
? Gesture.Pan()
|
|
246
|
+
.activeOffsetY(restOffset !== 0 ? [-10, 10] : closeDirection * 10)
|
|
247
|
+
.failOffsetX([-15, 15])
|
|
248
|
+
: Gesture.Pan()
|
|
249
|
+
.activeOffsetX(restOffset !== 0 ? [-10, 10] : closeDirection * 10)
|
|
250
|
+
.failOffsetY([-15, 15])
|
|
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
|
+
|
|
257
|
+
const handleGesture = handleAxisGesture
|
|
258
|
+
.enabled(open)
|
|
259
|
+
.onStart(() => {
|
|
260
|
+
'worklet'
|
|
261
|
+
gestureStartOffset.value = translateOffset.value
|
|
262
|
+
})
|
|
263
|
+
.onUpdate((event) => {
|
|
264
|
+
'worklet'
|
|
265
|
+
const translation = vertical ? event.translationY : event.translationX
|
|
266
|
+
translateOffset.value = Math.min(clampMax, Math.max(clampMin, gestureStartOffset.value + translation))
|
|
267
|
+
})
|
|
268
|
+
.onEnd((event) => {
|
|
269
|
+
'worklet'
|
|
270
|
+
const velocity = vertical ? event.velocityY : event.velocityX
|
|
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
|
|
288
|
+
} else {
|
|
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
|
|
297
|
+
}
|
|
298
|
+
translateOffset.value = withSpring(target, SPRING)
|
|
299
|
+
if (closing) runOnJS(onClose)()
|
|
300
|
+
})
|
|
30
301
|
|
|
31
|
-
|
|
32
|
-
|
|
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.
|
|
306
|
+
const HANDLE_STRIP_THICKNESS = 28
|
|
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 }
|
|
336
|
+
const handlePillStyle: ViewStyle = vertical ? { height: 6, width: 64 } : { height: 64, width: 6 }
|
|
337
|
+
// react-native-web reads `cursor` straight off style; native ignores the unknown key. ViewStyle (the
|
|
338
|
+
// native type these files are typed against) has no such property, hence the cast.
|
|
339
|
+
const webCursorStyle = { cursor: Platform.OS === 'web' ? 'pointer' : undefined } as ViewStyle
|
|
33
340
|
|
|
34
|
-
|
|
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
|
+
})
|
|
35
353
|
|
|
36
354
|
return (
|
|
37
355
|
<>
|
|
38
|
-
<Animated.View style={[styles.backdrop, backdropStyle]} pointerEvents={open ? 'auto' : 'none'}>
|
|
356
|
+
<Animated.View style={[styles.backdrop, { zIndex }, backdropStyle]} pointerEvents={open && blockingBackdrop ? 'auto' : 'none'}>
|
|
39
357
|
<Pressable style={StyleSheet.absoluteFill} onPress={onClose} />
|
|
40
358
|
</Animated.View>
|
|
41
|
-
<Animated.View style={
|
|
359
|
+
<Animated.View style={drawerOuterStyle}>
|
|
360
|
+
{contentSize ? <View style={contentClipStyle}>{fill}</View> : fill}
|
|
361
|
+
{dismissible && (
|
|
362
|
+
<GestureDetector gesture={handleGesture}>
|
|
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>
|
|
364
|
+
</GestureDetector>
|
|
365
|
+
)}
|
|
366
|
+
</Animated.View>
|
|
42
367
|
</>
|
|
43
368
|
)
|
|
44
369
|
}
|
|
45
370
|
|
|
46
371
|
const styles = StyleSheet.create({
|
|
372
|
+
anchorBottom: {
|
|
373
|
+
bottom: 0,
|
|
374
|
+
left: 0,
|
|
375
|
+
right: 0
|
|
376
|
+
},
|
|
47
377
|
anchorLeft: {
|
|
48
|
-
|
|
378
|
+
bottom: 0,
|
|
379
|
+
left: 0,
|
|
380
|
+
top: 0
|
|
49
381
|
},
|
|
50
382
|
anchorRight: {
|
|
51
|
-
|
|
383
|
+
bottom: 0,
|
|
384
|
+
right: 0,
|
|
385
|
+
top: 0
|
|
386
|
+
},
|
|
387
|
+
anchorTop: {
|
|
388
|
+
left: 0,
|
|
389
|
+
right: 0,
|
|
390
|
+
top: 0
|
|
52
391
|
},
|
|
53
392
|
backdrop: {
|
|
54
393
|
backgroundColor: '#000',
|
|
@@ -56,13 +395,20 @@ const styles = StyleSheet.create({
|
|
|
56
395
|
left: 0,
|
|
57
396
|
position: 'absolute',
|
|
58
397
|
right: 0,
|
|
59
|
-
top: 0
|
|
60
|
-
|
|
398
|
+
top: 0
|
|
399
|
+
},
|
|
400
|
+
clip: {
|
|
401
|
+
overflow: 'hidden'
|
|
61
402
|
},
|
|
62
403
|
drawer: {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
404
|
+
position: 'absolute'
|
|
405
|
+
},
|
|
406
|
+
handlePill: {
|
|
407
|
+
borderRadius: 3
|
|
408
|
+
},
|
|
409
|
+
handleStrip: {
|
|
410
|
+
alignItems: 'center',
|
|
411
|
+
justifyContent: 'center',
|
|
412
|
+
position: 'absolute'
|
|
67
413
|
}
|
|
68
414
|
})
|
|
@@ -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
|
+
}
|
package/src/DrawerEdgeSwipe.tsx
CHANGED
|
@@ -2,52 +2,89 @@ 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 DrawerDimension, type DrawerSide, getOpenDirection, isVerticalSide } from './geometry'
|
|
6
|
+
import { useDrawerSize } from './useDrawerSize'
|
|
7
|
+
|
|
5
8
|
const EDGE_WIDTH = 24
|
|
6
|
-
|
|
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 }
|
|
7
12
|
const VELOCITY_THRESHOLD = 500
|
|
8
13
|
|
|
9
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
|
|
10
20
|
enabled?: boolean
|
|
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
|
|
11
28
|
onOpen: () => void
|
|
12
|
-
side?:
|
|
13
|
-
|
|
14
|
-
width
|
|
29
|
+
side?: DrawerSide
|
|
30
|
+
translateOffset: SharedValue<number>
|
|
31
|
+
width?: DrawerDimension
|
|
15
32
|
}
|
|
16
33
|
|
|
17
|
-
export const DrawerEdgeSwipe = ({ enabled = true, onOpen, side = 'left',
|
|
18
|
-
const
|
|
19
|
-
const
|
|
20
|
-
const
|
|
21
|
-
const
|
|
34
|
+
export const DrawerEdgeSwipe = ({ edgeInset = 0, enabled = true, height = 300, maxHeight, maxWidth, onOpen, side = 'left', translateOffset, width = 300 }: DrawerEdgeSwipeProps) => {
|
|
35
|
+
const vertical = isVerticalSide(side)
|
|
36
|
+
const { closedOffset, effectiveSize, restOffset } = useDrawerSize(side, vertical ? height : width, vertical ? maxHeight : maxWidth, edgeInset)
|
|
37
|
+
const openDirection = getOpenDirection(side)
|
|
38
|
+
const clampMin = Math.min(0, closedOffset)
|
|
39
|
+
const clampMax = Math.max(0, closedOffset)
|
|
40
|
+
|
|
41
|
+
const axisGesture = vertical
|
|
42
|
+
? Gesture.Pan()
|
|
43
|
+
.activeOffsetY(side === 'top' ? 10 : -10)
|
|
44
|
+
.failOffsetX([-15, 15])
|
|
45
|
+
: Gesture.Pan()
|
|
46
|
+
.activeOffsetX(side === 'left' ? 10 : -10)
|
|
47
|
+
.failOffsetY([-15, 15])
|
|
22
48
|
|
|
23
|
-
const gesture =
|
|
49
|
+
const gesture = axisGesture
|
|
24
50
|
.enabled(enabled)
|
|
25
|
-
.activeOffsetX(side === 'left' ? 10 : -10)
|
|
26
|
-
.failOffsetY([-15, 15])
|
|
27
51
|
.onUpdate((event) => {
|
|
28
52
|
'worklet'
|
|
29
|
-
|
|
53
|
+
const translation = vertical ? event.translationY : event.translationX
|
|
54
|
+
translateOffset.value = Math.min(clampMax, Math.max(clampMin, closedOffset + translation))
|
|
30
55
|
})
|
|
31
56
|
.onEnd((event) => {
|
|
32
57
|
'worklet'
|
|
33
|
-
const
|
|
58
|
+
const translation = vertical ? event.translationY : event.translationX
|
|
59
|
+
const velocity = vertical ? event.velocityY : event.velocityX
|
|
60
|
+
const commit = translation * openDirection > effectiveSize / 3 || velocity * openDirection > VELOCITY_THRESHOLD
|
|
34
61
|
if (commit) {
|
|
35
|
-
|
|
62
|
+
translateOffset.value = withSpring(restOffset, SPRING)
|
|
36
63
|
runOnJS(onOpen)()
|
|
37
64
|
} else {
|
|
38
|
-
|
|
65
|
+
translateOffset.value = withSpring(closedOffset, SPRING)
|
|
39
66
|
}
|
|
40
67
|
})
|
|
41
68
|
|
|
69
|
+
const edgeStyle = vertical ? [styles.edgeHorizontal, side === 'top' ? styles.top : styles.bottom] : [styles.edgeVertical, side === 'left' ? styles.left : styles.right]
|
|
70
|
+
|
|
42
71
|
return (
|
|
43
72
|
<GestureDetector gesture={gesture}>
|
|
44
|
-
<View style={
|
|
73
|
+
<View style={edgeStyle} />
|
|
45
74
|
</GestureDetector>
|
|
46
75
|
)
|
|
47
76
|
}
|
|
48
77
|
|
|
49
78
|
const styles = StyleSheet.create({
|
|
50
|
-
|
|
79
|
+
bottom: { bottom: 0 },
|
|
80
|
+
edgeHorizontal: {
|
|
81
|
+
height: EDGE_WIDTH,
|
|
82
|
+
left: 0,
|
|
83
|
+
position: 'absolute',
|
|
84
|
+
right: 0,
|
|
85
|
+
zIndex: 5
|
|
86
|
+
},
|
|
87
|
+
edgeVertical: {
|
|
51
88
|
bottom: 0,
|
|
52
89
|
position: 'absolute',
|
|
53
90
|
top: 0,
|
|
@@ -55,5 +92,6 @@ const styles = StyleSheet.create({
|
|
|
55
92
|
zIndex: 5
|
|
56
93
|
},
|
|
57
94
|
left: { left: 0 },
|
|
58
|
-
right: { right: 0 }
|
|
95
|
+
right: { right: 0 },
|
|
96
|
+
top: { top: 0 }
|
|
59
97
|
})
|