@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.
@@ -1,60 +1,188 @@
1
- import { createContext, JSX, ReactNode, useContext, useMemo, useState } from 'react'
2
- import { useSharedValue } from 'react-native-reanimated'
1
+ import { createContext, JSX, ReactNode, useContext, useEffect, useMemo, useState } from 'react'
2
+ import { BackHandler } from 'react-native'
3
+ import { type SharedValue, useDerivedValue, useSharedValue } from 'react-native-reanimated'
3
4
 
4
5
  import { Drawer } from './Drawer'
5
6
  import { DrawerEdgeSwipe } from './DrawerEdgeSwipe'
7
+ import { type DrawerDimension, type DrawerSide, getOpenDirection, isVerticalSide } from './geometry'
8
+ import { useDrawerSize } from './useDrawerSize'
6
9
 
7
10
  export type DrawerActions = {
8
11
  close: () => void
12
+ // 0 anywhere at or before `height`/`width` (closed, or resting at its default open size —
13
+ // nothing to indicate, since the panel isn't showing any more than that), 1 once a drag has
14
+ // pulled it all the way open to `maxHeight`/`maxWidth`, smoothly interpolating in between as the
15
+ // handle is dragged or the spring animates. For content that only needs to react once the panel
16
+ // is genuinely at its full extent — e.g. fading in a top safe-area inset that's wasted space while
17
+ // merely at rest, but genuinely needed once expansion reaches the screen edge/notch. This is the
18
+ // content-padding approach to a safe-area inset; `edgeInset` (see CreateDrawerOptions) is the
19
+ // alternative geometry-clamp approach, which keeps the panel itself short of the inset instead —
20
+ // don't combine both for the same edge on the same drawer, or the inset gets applied twice. Always
21
+ // a flat 1 while open (matching "already at full extent") when there's no maxHeight/maxWidth
22
+ // configured.
23
+ expandProgress: SharedValue<number>
9
24
  isOpen: boolean
25
+ // True from open() through the full close animation, only dropping to false once the panel has
26
+ // actually finished sliding away, unlike isOpen, which flips the instant close() is called. For
27
+ // anything that needs to stay above/alongside the panel for as long as it's visually on screen
28
+ // (e.g. a FAB row portaled above it) rather than disappearing the moment closing starts.
29
+ isVisible: boolean
10
30
  open: () => void
11
31
  }
12
32
 
13
33
  export type CreateDrawerOptions = {
14
- side?: 'left' | 'right'
15
- width?: number
34
+ backdropOpacity?: number
35
+ blockingBackdrop?: boolean
36
+ blur?: boolean
37
+ // Whether the Android hardware back button closes the drawer while it's open, instead of falling
38
+ // through to whatever screen/navigator is behind it. No-ops on iOS/web, where the underlying
39
+ // BackHandler event never fires.
40
+ closeOnBackPress?: boolean
41
+ contentSize?: boolean
42
+ dismissible?: boolean
43
+ // See Drawer's own edgeInset doc: shrinks the basis a *percentage* height/maxHeight/width/
44
+ // maxWidth resolves against, so `'100%'` stops this many px short of the screen edge instead of
45
+ // reaching it; a literal px value is unaffected. No per-mount override (like maxHeight/maxWidth,
46
+ // this is factory-level only) since it's meant to describe a fixed constraint of the device/app
47
+ // (a safe-area inset), not something that varies by where a given mount happens to be used.
48
+ edgeInset?: number
49
+ height?: DrawerDimension
50
+ // See Drawer's own maxHeight doc: caps how far a drag on the handle can expand the panel past
51
+ // `height`. No per-mount override (like height/width, this is factory-level only).
52
+ maxHeight?: DrawerDimension
53
+ // The maxWidth mirror of maxHeight, for `left`/`right` drawers.
54
+ maxWidth?: DrawerDimension
55
+ showHandle?: boolean
56
+ side?: DrawerSide
57
+ width?: DrawerDimension
58
+ // Stacking tier for this drawer's backdrop/panel/handle: see Drawer's own zIndex doc for the full
59
+ // rationale. Matters once more than one createDrawer() instance can be open at the same time: give
60
+ // whichever one should render on top a higher value than the other(s), independent of which
61
+ // DrawerInstanceProvider happens to be declared outermost/innermost.
62
+ zIndex?: number
16
63
  }
17
64
 
18
- export type DrawerProviderProps = {
19
- // Rest-of-app content the drawer's actions must be reachable from — a normal Provider children slot.
65
+ export type DrawerInstanceProviderProps = {
66
+ // Overrides the backdropOpacity passed to createDrawer() (if any) for this mount.
67
+ backdropOpacity?: number
68
+ // Overrides the blockingBackdrop passed to createDrawer() (if any) for this mount.
69
+ blockingBackdrop?: boolean
70
+ // Overrides the blur passed to createDrawer() (if any) for this mount; falls through to
71
+ // @rific/auto-paper's own useBlur() global preference when neither is set.
72
+ blur?: boolean
73
+ // Rest-of-app content the drawer's actions must be reachable from: a normal Provider children slot.
20
74
  children?: ReactNode
75
+ // Overrides the closeOnBackPress passed to createDrawer() (if any) for this mount.
76
+ closeOnBackPress?: boolean
21
77
  // The drawer panel's own content, rendered inside the sliding panel rather than as `children`.
22
78
  content?: ReactNode
79
+ // Overrides the contentSize passed to createDrawer() (if any) for this mount.
80
+ contentSize?: boolean
81
+ // Overrides the dismissible passed to createDrawer() (if any) for this mount.
82
+ dismissible?: boolean
23
83
  // Lets a screen temporarily suppress the edge-swipe gesture (e.g. while another drawer is open).
24
84
  enabled?: boolean
85
+ // Overrides the showHandle passed to createDrawer() (if any) for this mount.
86
+ showHandle?: boolean
87
+ // Overrides the zIndex passed to createDrawer() (if any) for this mount.
88
+ zIndex?: number
25
89
  }
26
90
 
27
91
  export type CreateDrawerResult = {
28
- DrawerProvider: (props: DrawerProviderProps) => JSX.Element
92
+ DrawerInstanceProvider: (props: DrawerInstanceProviderProps) => JSX.Element
29
93
  useDrawer: () => DrawerActions
30
94
  }
31
95
 
32
96
  const noop = () => {}
33
97
 
34
- // One call per drawer instance — each gets its own Context, so a left nav drawer and a right
98
+ // One call per drawer instance: each gets its own Context, so a left nav drawer and a right
35
99
  // settings drawer (say) stay fully independent without a stringly-typed id to keep them apart.
36
- export const createDrawer = ({ side = 'left', width = 300 }: CreateDrawerOptions = {}): CreateDrawerResult => {
37
- const DrawerActionsContext = createContext<DrawerActions>({ close: noop, isOpen: false, open: noop })
100
+ export const createDrawer = ({ backdropOpacity: factoryBackdropOpacity, blockingBackdrop: factoryBlockingBackdrop, blur: factoryBlur, closeOnBackPress: factoryCloseOnBackPress, contentSize: factoryContentSize, dismissible: factoryDismissible, edgeInset = 0, height = 300, maxHeight, maxWidth, showHandle: factoryShowHandle, side = 'left', width = 300, zIndex: factoryZIndex }: CreateDrawerOptions = {}): CreateDrawerResult => {
101
+ // Static, non-reactive stand-in for the default context value only (before any real Provider has
102
+ // mounted) — same reasoning as the plain `noop` functions alongside it.
103
+ const defaultExpandProgress = { value: 1 } as SharedValue<number>
104
+ const DrawerActionsContext = createContext<DrawerActions>({ close: noop, expandProgress: defaultExpandProgress, isOpen: false, isVisible: false, open: noop })
105
+ const vertical = isVerticalSide(side)
106
+ const size = vertical ? height : width
107
+ const maxSize = vertical ? maxHeight : maxWidth
108
+ const closeDirection = -getOpenDirection(side)
38
109
 
39
- const DrawerProvider = ({ children, content, enabled = true }: DrawerProviderProps): JSX.Element => {
110
+ const DrawerInstanceProvider = ({ backdropOpacity: backdropOpacityOverride, blockingBackdrop: blockingBackdropOverride, blur: blurOverride, children, closeOnBackPress: closeOnBackPressOverride, content, contentSize: contentSizeOverride, dismissible: dismissibleOverride, enabled = true, showHandle: showHandleOverride, zIndex: zIndexOverride }: DrawerInstanceProviderProps): JSX.Element => {
40
111
  const [isOpen, setIsOpen] = useState(false)
41
- const closedX = side === 'left' ? -width : width
42
- const translateX = useSharedValue(closedX)
112
+ // Starts in lockstep with isOpen (both false) and stays true past isOpen turning false, until
113
+ // Drawer's onClosed reports the outro spring has actually settled: see the isVisible field above.
114
+ const [isVisible, setIsVisible] = useState(false)
115
+ const [measuredSize, setMeasuredSize] = useState<number | null>(null)
116
+ const backdropOpacity = backdropOpacityOverride ?? factoryBackdropOpacity ?? 0.45
117
+ const blur = blurOverride ?? factoryBlur
118
+ const blockingBackdrop = blockingBackdropOverride ?? factoryBlockingBackdrop ?? true
119
+ const closeOnBackPress = closeOnBackPressOverride ?? factoryCloseOnBackPress ?? true
120
+ const contentSize = contentSizeOverride ?? factoryContentSize ?? false
121
+ const dismissible = dismissibleOverride ?? factoryDismissible ?? true
122
+ const showHandle = showHandleOverride ?? factoryShowHandle ?? true
123
+ const zIndex = zIndexOverride ?? factoryZIndex ?? 50
124
+
125
+ // Fed by Drawer's onMeasure, and forwarded (in place of the static option) to both Drawer and
126
+ // DrawerEdgeSwipe: DrawerEdgeSwipe's own commit-threshold math needs the live size too, but it
127
+ // stays agnostic of contentSize itself; it just receives whichever height/width value is current.
128
+ const effectiveSize = contentSize ? (measuredSize ?? size) : size
129
+
130
+ // Percentages can't resolve outside a component (no window dimensions to hand), so unlike
131
+ // Drawer/DrawerEdgeSwipe (which each resolve their own copy internally), this is the one place
132
+ // createDrawer needs it directly — both for translateOffset's own initial seed, and restOffset
133
+ // for expandProgress below. contentSize never gets a maxSize (mirrors Drawer's own
134
+ // contentSize-has-no-expand-ceiling rule), so expandProgress is always a flat 1 there too.
135
+ const { closedOffset, restOffset } = useDrawerSize(side, effectiveSize, contentSize ? undefined : maxSize, edgeInset)
136
+ const translateOffset = useSharedValue(closedOffset)
137
+ // See DrawerActions' own doc comment for what this computes, and geometry.ts's getExpandProgress
138
+ // (kept in sync, tested there directly) for the same formula explained in more depth. Inlined
139
+ // rather than calling that shared helper: react-native-worklets (Reanimated 4+) only forwards a
140
+ // worklet's *relative* imports for files matching an explicit allowlist, which doesn't include
141
+ // published node_modules packages by default — importing and calling it here would fail at
142
+ // runtime as an unrecognized cross-module "remote function" call from the UI thread. currentD/
143
+ // restD are in the same closeDirection-normalized "D-space" Drawer.tsx's own gesture math uses,
144
+ // so this stays agnostic of `side`'s sign convention.
145
+ const expandProgress = useDerivedValue(() => {
146
+ const currentD = translateOffset.value * closeDirection
147
+ const restD = restOffset * closeDirection
148
+ if (restD <= 0) return 1
149
+ return Math.min(1, Math.max(0, (restD - currentD) / restD))
150
+ })
151
+
152
+ const open = () => {
153
+ setIsOpen(true)
154
+ setIsVisible(true)
155
+ }
43
156
 
44
157
  const actions = useMemo<DrawerActions>(
45
158
  () => ({
46
159
  close: () => setIsOpen(false),
160
+ expandProgress,
47
161
  isOpen,
48
- open: () => setIsOpen(true)
162
+ isVisible,
163
+ open
49
164
  }),
50
- [isOpen]
165
+ [expandProgress, isOpen, isVisible]
51
166
  )
52
167
 
168
+ // Only subscribed while open, so the back button falls through to normal navigation the rest of
169
+ // the time. Returning true from the handler marks the press as consumed (RN's contract for
170
+ // hardwareBackPress), stopping it from also closing a screen/navigator behind the drawer.
171
+ useEffect(() => {
172
+ if (!isOpen || !closeOnBackPress) return
173
+
174
+ const subscription = BackHandler.addEventListener('hardwareBackPress', () => {
175
+ setIsOpen(false)
176
+ return true
177
+ })
178
+ return () => subscription.remove()
179
+ }, [isOpen, closeOnBackPress])
180
+
53
181
  return (
54
182
  <DrawerActionsContext.Provider value={actions}>
55
183
  {children}
56
- <DrawerEdgeSwipe enabled={enabled && !isOpen} onOpen={() => setIsOpen(true)} side={side} translateX={translateX} width={width} />
57
- <Drawer onClose={() => setIsOpen(false)} open={isOpen} side={side} translateX={translateX} width={width}>
184
+ <DrawerEdgeSwipe edgeInset={edgeInset} enabled={enabled && !isOpen} height={vertical ? effectiveSize : height} maxHeight={maxHeight} maxWidth={maxWidth} onOpen={open} side={side} translateOffset={translateOffset} width={vertical ? width : effectiveSize} />
185
+ <Drawer backdropOpacity={backdropOpacity} blockingBackdrop={blockingBackdrop} blur={blur} contentSize={contentSize} dismissible={dismissible} edgeInset={edgeInset} height={vertical ? effectiveSize : height} maxHeight={maxHeight} maxWidth={maxWidth} onClose={() => setIsOpen(false)} onClosed={() => setIsVisible(false)} onMeasure={setMeasuredSize} open={isOpen} showHandle={showHandle} side={side} translateOffset={translateOffset} width={vertical ? width : effectiveSize} zIndex={zIndex}>
58
186
  {content}
59
187
  </Drawer>
60
188
  </DrawerActionsContext.Provider>
@@ -63,15 +191,15 @@ export const createDrawer = ({ side = 'left', width = 300 }: CreateDrawerOptions
63
191
 
64
192
  const useDrawer = (): DrawerActions => useContext(DrawerActionsContext)
65
193
 
66
- return { DrawerProvider, useDrawer }
194
+ return { DrawerInstanceProvider, useDrawer }
67
195
  }
68
196
 
69
- export type DrawerProviderComponent = (props: DrawerProviderProps) => JSX.Element
197
+ export type DrawerInstanceProviderComponent = (props: DrawerInstanceProviderProps) => JSX.Element
70
198
 
71
199
  // Flattens nesting N createDrawer() providers under the root into a single wrapper. Each entry is
72
- // a [DrawerProvider, props] pair — props are that drawer's own content/enabled, forwarded as-is.
200
+ // a [DrawerInstanceProvider, props] pair: props are that drawer's own content/enabled, forwarded as-is.
73
201
  // Argument order is outer-to-inner, matching how you'd otherwise nest them by hand.
74
- export const combineDrawerProviders = (...entries: [DrawerProviderComponent, Omit<DrawerProviderProps, 'children'>?][]) => {
202
+ export const combineDrawerProviders = (...entries: [DrawerInstanceProviderComponent, Omit<DrawerInstanceProviderProps, 'children'>?][]) => {
75
203
  const CombinedDrawerProviders = ({ children }: { children?: ReactNode }): JSX.Element => entries.reduceRight<ReactNode>((acc, [Provider, props]) => <Provider {...props}>{acc}</Provider>, children) as JSX.Element
76
204
 
77
205
  return CombinedDrawerProviders
@@ -0,0 +1,52 @@
1
+ export type DrawerSide = 'left' | 'right' | 'top' | 'bottom'
2
+
3
+ // A plain pixel value, or a percentage of the relevant screen dimension (window height for
4
+ // top/bottom, window width for left/right) — see resolveDimension.
5
+ export type DrawerDimension = number | `${number}%`
6
+
7
+ export function isVerticalSide(side: DrawerSide): boolean {
8
+ return side === 'top' || side === 'bottom'
9
+ }
10
+
11
+ // left/top start at a negative offset (slide toward 0, i.e. positive, to open);
12
+ // right/bottom start at a positive offset (slide toward 0, i.e. negative, to open). The size === 0
13
+ // special case (hit whenever a drawer has no maxHeight/maxWidth, since restOffset is then computed
14
+ // from a 0 gap) sidesteps `-size` producing -0 for left/top: functionally identical to 0 for any
15
+ // animation/comparison math, but distinct under Object.is, which trips up naive equality checks.
16
+ export function getClosedOffset(side: DrawerSide, size: number): number {
17
+ return size === 0 ? 0 : side === 'left' || side === 'top' ? -size : size
18
+ }
19
+
20
+ // Which drag direction (along the relevant axis) counts as "opening".
21
+ export function getOpenDirection(side: DrawerSide): 1 | -1 {
22
+ return side === 'left' || side === 'top' ? 1 : -1
23
+ }
24
+
25
+ // Numbers pass through untouched; a percentage string resolves against whichever window
26
+ // dimension is relevant for the drawer's axis (its caller picks height vs width).
27
+ export function resolveDimension(value: DrawerDimension, windowSize: number): number {
28
+ return typeof value === 'number' ? value : (Number.parseFloat(value) / 100) * windowSize
29
+ }
30
+
31
+ // How far past `height`/`width` (its rest size) an expandable sheet currently is, as a 0-1
32
+ // fraction: 0 anywhere at or before rest (closed, or resting — nothing to indicate, since the
33
+ // panel isn't showing any more than its configured rest size), 1 once fully expanded to
34
+ // `maxHeight`/`maxWidth`, ramping smoothly in between. For content that only needs to react once
35
+ // the panel is actually at its full extent — e.g. a top safe-area inset that's wasted space while
36
+ // merely at rest, but genuinely needed once expansion reaches the screen edge/notch.
37
+ // currentD/restD are both expected in the same closeDirection-normalized "D-space" the gesture
38
+ // math elsewhere uses (0 = fully expanded, larger = closer to closed), so this stays agnostic of
39
+ // `side`'s sign convention. restD <= 0 (no maxHeight/maxWidth configured, or a degenerate config)
40
+ // means there's no expand range to speak of: rest already IS the full extent, so this is always 1.
41
+ // NOT actually called from createDrawer.tsx's useDerivedValue at runtime, despite computing the
42
+ // exact same thing — deliberately duplicated inline there instead (see its own comment) rather
43
+ // than imported, since react-native-worklets (Reanimated 4+) only forwards a worklet's *relative*
44
+ // imports for files matching an explicit allowlist, which a published node_modules package like
45
+ // this one isn't part of by default; an imported (not inlined) function called from inside a
46
+ // worklet then fails at runtime as an unrecognized "remote function" call. This copy exists so the
47
+ // interesting interpolation math (which createDrawer's own open/close-only test API can't reach)
48
+ // still has a direct, isolated test — keep both in sync if this formula ever changes.
49
+ export function getExpandProgress(currentD: number, restD: number): number {
50
+ if (restD <= 0) return 1
51
+ return Math.min(1, Math.max(0, (restD - currentD) / restD))
52
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,5 @@
1
- export { combineDrawerProviders, createDrawer, type CreateDrawerOptions, type CreateDrawerResult, type DrawerActions, type DrawerProviderComponent, type DrawerProviderProps } from './createDrawer'
1
+ export { combineDrawerProviders, createDrawer, type CreateDrawerOptions, type CreateDrawerResult, type DrawerActions, type DrawerInstanceProviderComponent, type DrawerInstanceProviderProps } from './createDrawer'
2
2
  export { Drawer, type DrawerProps } from './Drawer'
3
+ export { type AutoPaperModule, configureDrawer, type DrawerConfig, DrawerProvider, type DrawerProviderProps, getDrawerConfig } from './DrawerConfig'
3
4
  export { DrawerEdgeSwipe, type DrawerEdgeSwipeProps } from './DrawerEdgeSwipe'
5
+ export { type DrawerDimension, type DrawerSide } from './geometry'
@@ -0,0 +1,55 @@
1
+ import { useWindowDimensions } from 'react-native'
2
+
3
+ import { type DrawerDimension, type DrawerSide, getClosedOffset, isVerticalSide, resolveDimension } from './geometry'
4
+
5
+ export type DrawerSize = {
6
+ // The panel's rest size, in px: what it opens to by default, and what a drag-to-close gesture
7
+ // measures its 1/3-of-the-way commit threshold against.
8
+ effectiveSize: number
9
+ // Where a drag-to-close gesture (or the closed side of DrawerEdgeSwipe) lands: fully off-screen
10
+ // relative to the panel's rendered (max) size, not just its rest size.
11
+ closedOffset: number
12
+ // The panel's rendered box size, in px: equal to effectiveSize unless maxSize is given and
13
+ // resolves larger, in which case the panel renders at this larger size and sits mostly
14
+ // off-screen at rest, revealed by dragging past the rest position (see restOffset).
15
+ maxEffectiveSize: number
16
+ // Where `open` rests by default: 0 (fully expanded) when there's no maxSize (or it resolves to
17
+ // effectiveSize), otherwise the offset that leaves exactly effectiveSize px on screen, with the
18
+ // remainder (maxEffectiveSize - effectiveSize) sitting off-screen until dragged open further.
19
+ restOffset: number
20
+ }
21
+
22
+ // Resolves a drawer's percentage-or-px size props (and optional expand ceiling) against the
23
+ // current window size into concrete offsets, shared by Drawer, DrawerEdgeSwipe, and createDrawer
24
+ // so all three always agree on where "closed"/"rest"/"expanded" actually are.
25
+ //
26
+ // edgeInset (px, default 0) shrinks the basis a *percentage* height/width/maxHeight/maxWidth
27
+ // resolves against — windowSize - edgeInset instead of the raw windowSize — so `'100%'` fills
28
+ // exactly up to that boundary (e.g. `edgeInset={insets.top}` on a `bottom` sheet's `maxHeight:
29
+ // '100%'` stops it just short of the status bar/notch instead of sliding behind it) rather than
30
+ // the literal screen edge. This is the geometry-clamp alternative to padding `content` away from a
31
+ // safe-area inset (see the README's Safe area section): the panel itself never reaches the inset,
32
+ // so there's nothing inside `content` to compensate for — don't combine the two for the same edge,
33
+ // or the inset ends up applied twice.
34
+ //
35
+ // A plain pixel number is deliberately left untouched by edgeInset (resolveDimension ignores its
36
+ // windowSize argument entirely for numbers, so passing the shrunk basis to it is a no-op there):
37
+ // a percentage means "fill the available space," which should already account for a known inset,
38
+ // while a literal px value means "this exact size," typically one the caller already computed
39
+ // deliberately (including, if they want, against an inset themselves) — edgeInset silently
40
+ // overriding that would take away the one way to opt back out of it for a specific drawer.
41
+ export function useDrawerSize(side: DrawerSide, size: DrawerDimension, maxSize?: DrawerDimension, edgeInset = 0): DrawerSize {
42
+ const windowDimensions = useWindowDimensions()
43
+ const windowSize = isVerticalSide(side) ? windowDimensions.height : windowDimensions.width
44
+ const percentBasis = windowSize - edgeInset
45
+
46
+ const effectiveSize = resolveDimension(size, percentBasis)
47
+ // Guards a misconfigured maxSize smaller than size, which would otherwise produce a negative
48
+ // "hidden" range and invert the rest/closed math below.
49
+ const maxEffectiveSize = maxSize === undefined ? effectiveSize : Math.max(resolveDimension(maxSize, percentBasis), effectiveSize)
50
+
51
+ const closedOffset = getClosedOffset(side, maxEffectiveSize)
52
+ const restOffset = getClosedOffset(side, maxEffectiveSize - effectiveSize)
53
+
54
+ return { closedOffset, effectiveSize, maxEffectiveSize, restOffset }
55
+ }