@rific/drawer 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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)
@@ -1,16 +1,29 @@
1
1
  import { createContext, JSX, ReactNode, useContext, useEffect, useMemo, useState } from 'react'
2
2
  import { BackHandler } from 'react-native'
3
- import { useSharedValue } from 'react-native-reanimated'
3
+ import { type SharedValue, useDerivedValue, useSharedValue } from 'react-native-reanimated'
4
4
 
5
5
  import { Drawer } from './Drawer'
6
6
  import { DrawerEdgeSwipe } from './DrawerEdgeSwipe'
7
- import { type DrawerSide, getClosedOffset, isVerticalSide } from './geometry'
7
+ import { type DrawerDimension, type DrawerSide, getOpenDirection, isVerticalSide } from './geometry'
8
+ import { useDrawerSize } from './useDrawerSize'
8
9
 
9
10
  export type DrawerActions = {
10
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>
11
24
  isOpen: boolean
12
25
  // True from open() through the full close animation, only dropping to false once the panel has
13
- // actually finished sliding away — unlike isOpen, which flips the instant close() is called. For
26
+ // actually finished sliding away, unlike isOpen, which flips the instant close() is called. For
14
27
  // anything that needs to stay above/alongside the panel for as long as it's visually on screen
15
28
  // (e.g. a FAB row portaled above it) rather than disappearing the moment closing starts.
16
29
  isVisible: boolean
@@ -27,18 +40,29 @@ export type CreateDrawerOptions = {
27
40
  closeOnBackPress?: boolean
28
41
  contentSize?: boolean
29
42
  dismissible?: boolean
30
- height?: number
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
31
55
  showHandle?: boolean
32
56
  side?: DrawerSide
33
- width?: number
34
- // Stacking tier for this drawer's backdrop/panel/handle — see Drawer's own zIndex doc for the full
57
+ width?: DrawerDimension
58
+ // Stacking tier for this drawer's backdrop/panel/handle: see Drawer's own zIndex doc for the full
35
59
  // rationale. Matters once more than one createDrawer() instance can be open at the same time: give
36
60
  // whichever one should render on top a higher value than the other(s), independent of which
37
- // DrawerProvider happens to be declared outermost/innermost.
61
+ // DrawerInstanceProvider happens to be declared outermost/innermost.
38
62
  zIndex?: number
39
63
  }
40
64
 
41
- export type DrawerProviderProps = {
65
+ export type DrawerInstanceProviderProps = {
42
66
  // Overrides the backdropOpacity passed to createDrawer() (if any) for this mount.
43
67
  backdropOpacity?: number
44
68
  // Overrides the blockingBackdrop passed to createDrawer() (if any) for this mount.
@@ -46,7 +70,7 @@ export type DrawerProviderProps = {
46
70
  // Overrides the blur passed to createDrawer() (if any) for this mount; falls through to
47
71
  // @rific/auto-paper's own useBlur() global preference when neither is set.
48
72
  blur?: boolean
49
- // Rest-of-app content the drawer's actions must be reachable from — a normal Provider children slot.
73
+ // Rest-of-app content the drawer's actions must be reachable from: a normal Provider children slot.
50
74
  children?: ReactNode
51
75
  // Overrides the closeOnBackPress passed to createDrawer() (if any) for this mount.
52
76
  closeOnBackPress?: boolean
@@ -65,27 +89,30 @@ export type DrawerProviderProps = {
65
89
  }
66
90
 
67
91
  export type CreateDrawerResult = {
68
- DrawerProvider: (props: DrawerProviderProps) => JSX.Element
92
+ DrawerInstanceProvider: (props: DrawerInstanceProviderProps) => JSX.Element
69
93
  useDrawer: () => DrawerActions
70
94
  }
71
95
 
72
96
  const noop = () => {}
73
97
 
74
- // 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
75
99
  // settings drawer (say) stay fully independent without a stringly-typed id to keep them apart.
76
- export const createDrawer = ({ backdropOpacity: factoryBackdropOpacity, blockingBackdrop: factoryBlockingBackdrop, blur: factoryBlur, closeOnBackPress: factoryCloseOnBackPress, contentSize: factoryContentSize, dismissible: factoryDismissible, height = 300, showHandle: factoryShowHandle, side = 'left', width = 300, zIndex: factoryZIndex }: CreateDrawerOptions = {}): CreateDrawerResult => {
77
- const DrawerActionsContext = createContext<DrawerActions>({ close: noop, isOpen: false, isVisible: 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 })
78
105
  const vertical = isVerticalSide(side)
79
106
  const size = vertical ? height : width
80
- const closedOffset = getClosedOffset(side, size)
107
+ const maxSize = vertical ? maxHeight : maxWidth
108
+ const closeDirection = -getOpenDirection(side)
81
109
 
82
- const DrawerProvider = ({ backdropOpacity: backdropOpacityOverride, blockingBackdrop: blockingBackdropOverride, blur: blurOverride, children, closeOnBackPress: closeOnBackPressOverride, content, contentSize: contentSizeOverride, dismissible: dismissibleOverride, enabled = true, showHandle: showHandleOverride, zIndex: zIndexOverride }: 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 => {
83
111
  const [isOpen, setIsOpen] = useState(false)
84
112
  // Starts in lockstep with isOpen (both false) and stays true past isOpen turning false, until
85
- // Drawer's onClosed reports the outro spring has actually settled — see the isVisible field above.
113
+ // Drawer's onClosed reports the outro spring has actually settled: see the isVisible field above.
86
114
  const [isVisible, setIsVisible] = useState(false)
87
115
  const [measuredSize, setMeasuredSize] = useState<number | null>(null)
88
- const translateOffset = useSharedValue(closedOffset)
89
116
  const backdropOpacity = backdropOpacityOverride ?? factoryBackdropOpacity ?? 0.45
90
117
  const blur = blurOverride ?? factoryBlur
91
118
  const blockingBackdrop = blockingBackdropOverride ?? factoryBlockingBackdrop ?? true
@@ -96,10 +123,32 @@ export const createDrawer = ({ backdropOpacity: factoryBackdropOpacity, blocking
96
123
  const zIndex = zIndexOverride ?? factoryZIndex ?? 50
97
124
 
98
125
  // Fed by Drawer's onMeasure, and forwarded (in place of the static option) to both Drawer and
99
- // DrawerEdgeSwipe — DrawerEdgeSwipe's own commit-threshold math needs the live size too, but it
126
+ // DrawerEdgeSwipe: DrawerEdgeSwipe's own commit-threshold math needs the live size too, but it
100
127
  // stays agnostic of contentSize itself; it just receives whichever height/width value is current.
101
128
  const effectiveSize = contentSize ? (measuredSize ?? size) : size
102
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
+
103
152
  const open = () => {
104
153
  setIsOpen(true)
105
154
  setIsVisible(true)
@@ -108,11 +157,12 @@ export const createDrawer = ({ backdropOpacity: factoryBackdropOpacity, blocking
108
157
  const actions = useMemo<DrawerActions>(
109
158
  () => ({
110
159
  close: () => setIsOpen(false),
160
+ expandProgress,
111
161
  isOpen,
112
162
  isVisible,
113
163
  open
114
164
  }),
115
- [isOpen, isVisible]
165
+ [expandProgress, isOpen, isVisible]
116
166
  )
117
167
 
118
168
  // Only subscribed while open, so the back button falls through to normal navigation the rest of
@@ -131,8 +181,8 @@ export const createDrawer = ({ backdropOpacity: factoryBackdropOpacity, blocking
131
181
  return (
132
182
  <DrawerActionsContext.Provider value={actions}>
133
183
  {children}
134
- <DrawerEdgeSwipe enabled={enabled && !isOpen} height={vertical ? effectiveSize : height} onOpen={open} side={side} translateOffset={translateOffset} width={vertical ? width : effectiveSize} />
135
- <Drawer backdropOpacity={backdropOpacity} blockingBackdrop={blockingBackdrop} blur={blur} contentSize={contentSize} dismissible={dismissible} height={vertical ? effectiveSize : height} onClose={() => setIsOpen(false)} onClosed={() => setIsVisible(false)} onMeasure={setMeasuredSize} open={isOpen} showHandle={showHandle} side={side} translateOffset={translateOffset} width={vertical ? width : effectiveSize} zIndex={zIndex}>
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}>
136
186
  {content}
137
187
  </Drawer>
138
188
  </DrawerActionsContext.Provider>
@@ -141,15 +191,15 @@ export const createDrawer = ({ backdropOpacity: factoryBackdropOpacity, blocking
141
191
 
142
192
  const useDrawer = (): DrawerActions => useContext(DrawerActionsContext)
143
193
 
144
- return { DrawerProvider, useDrawer }
194
+ return { DrawerInstanceProvider, useDrawer }
145
195
  }
146
196
 
147
- export type DrawerProviderComponent = (props: DrawerProviderProps) => JSX.Element
197
+ export type DrawerInstanceProviderComponent = (props: DrawerInstanceProviderProps) => JSX.Element
148
198
 
149
199
  // Flattens nesting N createDrawer() providers under the root into a single wrapper. Each entry is
150
- // 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.
151
201
  // Argument order is outer-to-inner, matching how you'd otherwise nest them by hand.
152
- export const combineDrawerProviders = (...entries: [DrawerProviderComponent, Omit<DrawerProviderProps, 'children'>?][]) => {
202
+ export const combineDrawerProviders = (...entries: [DrawerInstanceProviderComponent, Omit<DrawerInstanceProviderProps, 'children'>?][]) => {
153
203
  const CombinedDrawerProviders = ({ children }: { children?: ReactNode }): JSX.Element => entries.reduceRight<ReactNode>((acc, [Provider, props]) => <Provider {...props}>{acc}</Provider>, children) as JSX.Element
154
204
 
155
205
  return CombinedDrawerProviders
package/src/geometry.ts CHANGED
@@ -1,16 +1,52 @@
1
1
  export type DrawerSide = 'left' | 'right' | 'top' | 'bottom'
2
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
+
3
7
  export function isVerticalSide(side: DrawerSide): boolean {
4
8
  return side === 'top' || side === 'bottom'
5
9
  }
6
10
 
7
11
  // left/top start at a negative offset (slide toward 0, i.e. positive, to open);
8
- // right/bottom start at a positive offset (slide toward 0, i.e. negative, 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.
9
16
  export function getClosedOffset(side: DrawerSide, size: number): number {
10
- return side === 'left' || side === 'top' ? -size : size
17
+ return size === 0 ? 0 : side === 'left' || side === 'top' ? -size : size
11
18
  }
12
19
 
13
20
  // Which drag direction (along the relevant axis) counts as "opening".
14
21
  export function getOpenDirection(side: DrawerSide): 1 | -1 {
15
22
  return side === 'left' || side === 'top' ? 1 : -1
16
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,4 +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'
4
- export { type DrawerSide } from './geometry'
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
+ }