react-modal-sheet 2.2.0 → 3.0.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,930 +0,0 @@
1
- import { useCallback, useEffect, useLayoutEffect, useRef, useState, createContext, useContext, createElement, forwardRef, useImperativeHandle, useMemo, Children, cloneElement } from 'react';
2
- import { createPortal } from 'react-dom';
3
- import { useMotionValue, useReducedMotion, useTransform, animate, motion, AnimatePresence } from 'framer-motion';
4
- import { useLayoutEffect as useLayoutEffect$1, isIOS, chain, getScrollParent } from '@react-aria/utils';
5
-
6
- function _extends() {
7
- _extends = Object.assign ? Object.assign.bind() : function (target) {
8
- for (var i = 1; i < arguments.length; i++) {
9
- var source = arguments[i];
10
- for (var key in source) {
11
- if (Object.prototype.hasOwnProperty.call(source, key)) {
12
- target[key] = source[key];
13
- }
14
- }
15
- }
16
- return target;
17
- };
18
- return _extends.apply(this, arguments);
19
- }
20
- function _objectWithoutPropertiesLoose(source, excluded) {
21
- if (source == null) return {};
22
- var target = {};
23
- var sourceKeys = Object.keys(source);
24
- var key, i;
25
- for (i = 0; i < sourceKeys.length; i++) {
26
- key = sourceKeys[i];
27
- if (excluded.indexOf(key) >= 0) continue;
28
- target[key] = source[key];
29
- }
30
- return target;
31
- }
32
-
33
- var MAX_HEIGHT = 'calc(100% - env(safe-area-inset-top) - 34px)';
34
- var IS_SSR = typeof window === 'undefined';
35
- var DEFAULT_TWEEN_CONFIG = {
36
- ease: 'easeOut',
37
- duration: 0.2
38
- };
39
- var REDUCED_MOTION_TWEEN_CONFIG = {
40
- ease: 'linear',
41
- duration: 0.01
42
- };
43
- var DRAG_CLOSE_THRESHOLD = 0.6;
44
- var DRAG_VELOCITY_THRESHOLD = 500;
45
-
46
- function getClosest(nums, goal) {
47
- var closest = nums[0];
48
- var minDifference = Math.abs(nums[0] - goal);
49
- for (var i = 1; i < nums.length; i++) {
50
- var difference = Math.abs(nums[i] - goal);
51
- if (difference < minDifference) {
52
- closest = nums[i];
53
- minDifference = difference;
54
- }
55
- }
56
- return closest;
57
- }
58
- function applyRootStyles(rootId) {
59
- var body = document.querySelector('body');
60
- var root = document.querySelector("#" + rootId);
61
- if (root) {
62
- var p = 24;
63
- var h = window.innerHeight;
64
- var s = (h - p) / h;
65
- body.style.backgroundColor = '#000';
66
- root.style.overflow = 'hidden';
67
- root.style.willChange = 'transform';
68
- root.style.transition = 'transform 200ms ease-in-out, border-radius 200ms linear';
69
- root.style.transform = "translateY(calc(env(safe-area-inset-top) + " + p / 2 + "px)) scale(" + s + ")"; // prettier-ignore
70
- root.style.borderTopRightRadius = '10px';
71
- root.style.borderTopLeftRadius = '10px';
72
- }
73
- }
74
- function cleanupRootStyles(rootId) {
75
- var body = document.querySelector('body');
76
- var root = document.getElementById(rootId);
77
- function onTransitionEnd() {
78
- root.style.removeProperty('overflow');
79
- root.style.removeProperty('will-change');
80
- root.style.removeProperty('transition');
81
- body.style.removeProperty('background-color');
82
- root.removeEventListener('transitionend', onTransitionEnd);
83
- }
84
- if (root) {
85
- // Start animating back
86
- root.style.removeProperty('border-top-right-radius');
87
- root.style.removeProperty('border-top-left-radius');
88
- root.style.removeProperty('transform');
89
- // Remove temp properties after animation is finished
90
- root.addEventListener('transitionend', onTransitionEnd);
91
- }
92
- }
93
- function inDescendingOrder(arr) {
94
- for (var i = 0; i < arr.length; i++) {
95
- if (arr[i + 1] > arr[i]) return false;
96
- }
97
- return true;
98
- }
99
- function validateSnapTo(_ref) {
100
- var snapTo = _ref.snapTo,
101
- sheetHeight = _ref.sheetHeight;
102
- if (snapTo < 0) {
103
- console.warn("Snap point is out of bounds. Sheet height is " + sheetHeight + " but snap point is " + (sheetHeight + Math.abs(snapTo)) + ".");
104
- }
105
- return Math.max(Math.round(snapTo), 0);
106
- }
107
- function mergeRefs(refs) {
108
- return function (value) {
109
- refs.forEach(function (ref) {
110
- if (typeof ref === 'function') {
111
- ref(value);
112
- } else if (ref) {
113
- ref.current = value;
114
- }
115
- });
116
- };
117
- }
118
- function isTouchDevice() {
119
- if (typeof window === 'undefined') return false;
120
- return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
121
- }
122
-
123
- var useIsomorphicLayoutEffect = IS_SSR ? useEffect : useLayoutEffect;
124
- function useModalEffect(isOpen, rootId) {
125
- var prevOpen = usePrevious(isOpen);
126
- // Automatically apply the iOS modal effect to the body when sheet opens/closes
127
- useEffect(function () {
128
- if (rootId && !prevOpen && isOpen) {
129
- applyRootStyles(rootId);
130
- } else if (rootId && !isOpen && prevOpen) {
131
- cleanupRootStyles(rootId);
132
- }
133
- }, [isOpen, prevOpen]); // eslint-disable-line
134
- // Make sure to cleanup modal styles on unmount
135
- useEffect(function () {
136
- return function () {
137
- if (rootId && isOpen) cleanupRootStyles(rootId);
138
- };
139
- }, [isOpen]); // eslint-disable-line
140
- }
141
-
142
- function useEventCallbacks(isOpen, callbacks) {
143
- var prevOpen = usePrevious(isOpen);
144
- var didOpen = useRef(false);
145
- // Because of AnimatePrecence we don't have access to latest isOpen value
146
- // so we need to read and write to a ref to determine if we are
147
- // opening or closing the sheet
148
- var handleAnimationComplete = useCallback(function () {
149
- if (!didOpen.current) {
150
- callbacks.current.onOpenEnd == null || callbacks.current.onOpenEnd();
151
- didOpen.current = true;
152
- } else {
153
- callbacks.current.onCloseEnd == null || callbacks.current.onCloseEnd();
154
- didOpen.current = false;
155
- }
156
- }, [isOpen, prevOpen]); // eslint-disable-line
157
- useEffect(function () {
158
- if (!prevOpen && isOpen) {
159
- callbacks.current.onOpenStart == null || callbacks.current.onOpenStart();
160
- } else if (!isOpen && prevOpen) {
161
- callbacks.current.onCloseStart == null || callbacks.current.onCloseStart();
162
- }
163
- }, [isOpen, prevOpen]); // eslint-disable-line
164
- return {
165
- handleAnimationComplete: handleAnimationComplete
166
- };
167
- }
168
- function useWindowHeight() {
169
- var _React$useState = useState(0),
170
- windowHeight = _React$useState[0],
171
- setWindowHeight = _React$useState[1];
172
- useIsomorphicLayoutEffect(function () {
173
- var updateHeight = function updateHeight() {
174
- return setWindowHeight(window.innerHeight);
175
- };
176
- window.addEventListener('resize', updateHeight);
177
- updateHeight();
178
- return function () {
179
- return window.removeEventListener('resize', updateHeight);
180
- };
181
- }, []);
182
- return windowHeight;
183
- }
184
- function usePrevious(state) {
185
- var ref = useRef();
186
- useEffect(function () {
187
- ref.current = state;
188
- });
189
- return ref.current;
190
- }
191
- // Userland version of the `useEvent` React hook:
192
- // RFC: https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md
193
- function useEvent(handler) {
194
- var handlerRef = useRef();
195
- useIsomorphicLayoutEffect(function () {
196
- handlerRef.current = handler;
197
- });
198
- return useCallback(function () {
199
- var fn = handlerRef.current;
200
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
201
- args[_key] = arguments[_key];
202
- }
203
- return fn == null ? void 0 : fn.apply(void 0, args);
204
- }, []);
205
- }
206
- // This is a hacky way to fix a bug in framer-motion where the drag
207
- // constraints are not updated when window is resized.
208
- // https://github.com/framer/motion/issues/1659
209
- var constraints = {
210
- bottom: 0,
211
- top: 0,
212
- left: 0,
213
- right: 0
214
- };
215
- function useDragConstraints() {
216
- var constraintsRef = useRef(null);
217
- var onMeasureDragConstraints = useCallback(function () {
218
- return constraints;
219
- }, []);
220
- return {
221
- constraintsRef: constraintsRef,
222
- onMeasureDragConstraints: onMeasureDragConstraints
223
- };
224
- }
225
-
226
- var SheetContext = /*#__PURE__*/createContext(undefined);
227
- var useSheetContext = function useSheetContext() {
228
- var context = useContext(SheetContext);
229
- if (!context) throw Error('Sheet context error');
230
- return context;
231
- };
232
- var SheetScrollerContext = /*#__PURE__*/createContext(undefined);
233
- function SheetScrollerContextProvider(_ref) {
234
- var children = _ref.children;
235
- var sheetContext = useSheetContext();
236
- var _React$useState = useState(!!sheetContext.disableDrag),
237
- disableDrag = _React$useState[0],
238
- setDisableDrag = _React$useState[1];
239
- function setDragEnabled() {
240
- if (!sheetContext.disableDrag) setDisableDrag(false);
241
- }
242
- function setDragDisabled() {
243
- if (!disableDrag) setDisableDrag(true);
244
- }
245
- return createElement(SheetScrollerContext.Provider, {
246
- value: {
247
- disableDrag: disableDrag,
248
- setDragEnabled: setDragEnabled,
249
- setDragDisabled: setDragDisabled
250
- }
251
- }, children);
252
- }
253
- var useSheetScrollerContext = function useSheetScrollerContext() {
254
- var context = useContext(SheetScrollerContext);
255
- if (!context) throw Error('Sheet scroller context error');
256
- return context;
257
- };
258
-
259
- // Source: https://github.com/adobe/react-spectrum/blob/main/packages/@react-aria/overlays/src/usePreventScroll.ts
260
- // @ts-ignore
261
- var visualViewport = typeof window !== 'undefined' && window.visualViewport;
262
- // HTML input types that do not cause the software keyboard to appear.
263
- var nonTextInputTypes = /*#__PURE__*/new Set(['checkbox', 'radio', 'range', 'color', 'file', 'image', 'button', 'submit', 'reset']);
264
- // The number of active usePreventScroll calls. Used to determine whether to revert back to the original page style/scroll position
265
- var preventScrollCount = 0;
266
- var restore;
267
- /**
268
- * Prevents scrolling on the document body on mount, and
269
- * restores it on unmount. Also ensures that content does not
270
- * shift due to the scrollbars disappearing.
271
- */
272
- function usePreventScroll(options) {
273
- if (options === void 0) {
274
- options = {};
275
- }
276
- var _options = options,
277
- isDisabled = _options.isDisabled;
278
- useLayoutEffect$1(function () {
279
- if (isDisabled) {
280
- return;
281
- }
282
- preventScrollCount++;
283
- if (preventScrollCount === 1) {
284
- if (isIOS()) {
285
- restore = preventScrollMobileSafari();
286
- } else {
287
- restore = preventScrollStandard();
288
- }
289
- }
290
- return function () {
291
- preventScrollCount--;
292
- if (preventScrollCount === 0) {
293
- restore();
294
- }
295
- };
296
- }, [isDisabled]);
297
- }
298
- // For most browsers, all we need to do is set `overflow: hidden` on the root element, and
299
- // add some padding to prevent the page from shifting when the scrollbar is hidden.
300
- function preventScrollStandard() {
301
- return chain(setStyle(document.documentElement, 'paddingRight', window.innerWidth - document.documentElement.clientWidth + "px"), setStyle(document.documentElement, 'overflow', 'hidden'));
302
- }
303
- // Mobile Safari is a whole different beast. Even with overflow: hidden,
304
- // it still scrolls the page in many situations:
305
- //
306
- // 1. When the bottom toolbar and address bar are collapsed, page scrolling is always allowed.
307
- // 2. When the keyboard is visible, the viewport does not resize. Instead, the keyboard covers part of
308
- // it, so it becomes scrollable.
309
- // 3. When tapping on an input, the page always scrolls so that the input is centered in the visual viewport.
310
- // This may cause even fixed position elements to scroll off the screen.
311
- // 4. When using the next/previous buttons in the keyboard to navigate between inputs, the whole page always
312
- // scrolls, even if the input is inside a nested scrollable element that could be scrolled instead.
313
- //
314
- // In order to work around these cases, and prevent scrolling without jankiness, we do a few things:
315
- //
316
- // 1. Prevent default on `touchmove` events that are not in a scrollable element. This prevents touch scrolling
317
- // on the window.
318
- // 2. Prevent default on `touchmove` events inside a scrollable element when the scroll position is at the
319
- // top or bottom. This avoids the whole page scrolling instead, but does prevent overscrolling.
320
- // 3. Prevent default on `touchend` events on input elements and handle focusing the element ourselves.
321
- // 4. When focusing an input, apply a transform to trick Safari into thinking the input is at the top
322
- // of the page, which prevents it from scrolling the page. After the input is focused, scroll the element
323
- // into view ourselves, without scrolling the whole page.
324
- // 5. Offset the body by the scroll position using a negative margin and scroll to the top. This should appear the
325
- // same visually, but makes the actual scroll position always zero. This is required to make all of the
326
- // above work or Safari will still try to scroll the page when focusing an input.
327
- // 6. As a last resort, handle window scroll events, and scroll back to the top. This can happen when attempting
328
- // to navigate to an input with the next/previous buttons that's outside a modal.
329
- function preventScrollMobileSafari() {
330
- var scrollable;
331
- var lastY = 0;
332
- var onTouchStart = function onTouchStart(e) {
333
- // Store the nearest scrollable parent element from the element that the user touched.
334
- scrollable = getScrollParent(e.target);
335
- if (scrollable === document.documentElement && scrollable === document.body) {
336
- return;
337
- }
338
- lastY = e.changedTouches[0].pageY;
339
- };
340
- var onTouchMove = function onTouchMove(e) {
341
- // Prevent scrolling the window.
342
- if (scrollable === document.documentElement || scrollable === document.body) {
343
- e.preventDefault();
344
- return;
345
- }
346
- // Prevent scrolling up when at the top and scrolling down when at the bottom
347
- // of a nested scrollable area, otherwise mobile Safari will start scrolling
348
- // the window instead. Unfortunately, this disables bounce scrolling when at
349
- // the top but it's the best we can do.
350
- var y = e.changedTouches[0].pageY;
351
- var scrollTop = scrollable.scrollTop;
352
- var bottom = scrollable.scrollHeight - scrollable.clientHeight;
353
- // Fix for: https://github.com/adobe/react-spectrum/pull/3780/files
354
- if (bottom === 0) {
355
- return;
356
- }
357
- if (scrollTop <= 0 && y > lastY || scrollTop >= bottom && y < lastY) {
358
- e.preventDefault();
359
- }
360
- lastY = y;
361
- };
362
- var onTouchEnd = function onTouchEnd(e) {
363
- var target = e.target;
364
- // Apply this change if we're not already focused on the target element
365
- if (willOpenKeyboard(target) && target !== document.activeElement) {
366
- e.preventDefault();
367
- // Apply a transform to trick Safari into thinking the input is at the top of the page
368
- // so it doesn't try to scroll it into view. When tapping on an input, this needs to
369
- // be done before the "focus" event, so we have to focus the element ourselves.
370
- target.style.transform = 'translateY(-2000px)';
371
- target.focus();
372
- requestAnimationFrame(function () {
373
- target.style.transform = '';
374
- });
375
- }
376
- };
377
- var onFocus = function onFocus(e) {
378
- var target = e.target;
379
- if (willOpenKeyboard(target)) {
380
- // Transform also needs to be applied in the focus event in cases where focus moves
381
- // other than tapping on an input directly, e.g. the next/previous buttons in the
382
- // software keyboard. In these cases, it seems applying the transform in the focus event
383
- // is good enough, whereas when tapping an input, it must be done before the focus event. 🤷‍♂️
384
- target.style.transform = 'translateY(-2000px)';
385
- requestAnimationFrame(function () {
386
- target.style.transform = '';
387
- // This will have prevented the browser from scrolling the focused element into view,
388
- // so we need to do this ourselves in a way that doesn't cause the whole page to scroll.
389
- if (visualViewport) {
390
- if (visualViewport.height < window.innerHeight) {
391
- // If the keyboard is already visible, do this after one additional frame
392
- // to wait for the transform to be removed.
393
- requestAnimationFrame(function () {
394
- scrollIntoView(target);
395
- });
396
- } else {
397
- // Otherwise, wait for the visual viewport to resize before scrolling so we can
398
- // measure the correct position to scroll to.
399
- visualViewport.addEventListener('resize', function () {
400
- return scrollIntoView(target);
401
- }, {
402
- once: true
403
- });
404
- }
405
- }
406
- });
407
- }
408
- };
409
- var onWindowScroll = function onWindowScroll() {
410
- // Last resort. If the window scrolled, scroll it back to the top.
411
- // It should always be at the top because the body will have a negative margin (see below).
412
- window.scrollTo(0, 0);
413
- };
414
- // Record the original scroll position so we can restore it.
415
- // Then apply a negative margin to the body to offset it by the scroll position. This will
416
- // enable us to scroll the window to the top, which is required for the rest of this to work.
417
- var scrollX = window.pageXOffset;
418
- var scrollY = window.pageYOffset;
419
- var restoreStyles = chain(setStyle(document.documentElement, 'paddingRight', window.innerWidth - document.documentElement.clientWidth + "px"), setStyle(document.documentElement, 'overflow', 'hidden'), setStyle(document.body, 'marginTop', "-" + scrollY + "px"));
420
- // Scroll to the top. The negative margin on the body will make this appear the same.
421
- window.scrollTo(0, 0);
422
- var removeEvents = chain(addEvent(document, 'touchstart', onTouchStart, {
423
- passive: false,
424
- capture: true
425
- }), addEvent(document, 'touchmove', onTouchMove, {
426
- passive: false,
427
- capture: true
428
- }), addEvent(document, 'touchend', onTouchEnd, {
429
- passive: false,
430
- capture: true
431
- }), addEvent(document, 'focus', onFocus, true), addEvent(window, 'scroll', onWindowScroll));
432
- return function () {
433
- // Restore styles and scroll the page back to where it was.
434
- restoreStyles();
435
- removeEvents();
436
- window.scrollTo(scrollX, scrollY);
437
- };
438
- }
439
- // Sets a CSS property on an element, and returns a function to revert it to the previous value.
440
- function setStyle(element, style, value) {
441
- var cur = element.style[style];
442
- element.style[style] = value;
443
- return function () {
444
- element.style[style] = cur;
445
- };
446
- }
447
- // Adds an event listener to an element, and returns a function to remove it.
448
- function addEvent(target, event, handler, options) {
449
- target.addEventListener(event, handler, options);
450
- return function () {
451
- target.removeEventListener(event, handler, options);
452
- };
453
- }
454
- function scrollIntoView(target) {
455
- var root = document.scrollingElement || document.documentElement;
456
- while (target && target !== root) {
457
- // Find the parent scrollable element and adjust the scroll position if the target is not already in view.
458
- var scrollable = getScrollParent(target);
459
- if (scrollable !== document.documentElement && scrollable !== document.body && scrollable !== target) {
460
- var scrollableTop = scrollable.getBoundingClientRect().top;
461
- var targetTop = target.getBoundingClientRect().top;
462
- if (targetTop > scrollableTop + target.clientHeight) {
463
- scrollable.scrollTop += targetTop - scrollableTop;
464
- }
465
- }
466
- target = scrollable.parentElement;
467
- }
468
- }
469
- function willOpenKeyboard(target) {
470
- return target instanceof HTMLInputElement && !nonTextInputTypes.has(target.type) || target instanceof HTMLTextAreaElement || target instanceof HTMLElement && target.isContentEditable;
471
- }
472
-
473
- var styles = {
474
- wrapper: {
475
- position: 'fixed',
476
- top: 0,
477
- bottom: 0,
478
- left: 0,
479
- right: 0,
480
- overflow: 'hidden',
481
- pointerEvents: 'none'
482
- },
483
- backdrop: {
484
- zIndex: 1,
485
- position: 'fixed',
486
- top: 0,
487
- left: 0,
488
- width: '100%',
489
- height: '100%',
490
- backgroundColor: 'rgba(0, 0, 0, 0.2)',
491
- touchAction: 'none',
492
- border: 'none'
493
- },
494
- container: {
495
- zIndex: 2,
496
- position: 'absolute',
497
- left: 0,
498
- bottom: 0,
499
- width: '100%',
500
- backgroundColor: '#fff',
501
- borderTopRightRadius: '8px',
502
- borderTopLeftRadius: '8px',
503
- boxShadow: '0px -2px 16px rgba(0, 0, 0, 0.3)',
504
- display: 'flex',
505
- flexDirection: 'column',
506
- pointerEvents: 'auto'
507
- },
508
- headerWrapper: {
509
- width: '100%'
510
- },
511
- header: {
512
- height: '40px',
513
- width: '100%',
514
- position: 'relative',
515
- display: 'flex',
516
- alignItems: 'center',
517
- justifyContent: 'center'
518
- },
519
- indicator: {
520
- width: '18px',
521
- height: '4px',
522
- borderRadius: '99px',
523
- backgroundColor: '#ddd'
524
- },
525
- content: {
526
- flexGrow: 1,
527
- display: 'flex',
528
- flexDirection: 'column',
529
- minHeight: '0px',
530
- position: 'relative'
531
- },
532
- scroller: {
533
- height: '100%',
534
- overflowY: 'auto'
535
- }
536
- };
537
-
538
- var _excluded = ["onOpenStart", "onOpenEnd", "onClose", "onCloseStart", "onCloseEnd", "onSnap", "children", "disableScrollLocking", "isOpen", "snapPoints", "rootId", "mountPoint", "style", "detent", "initialSnap", "disableDrag", "prefersReducedMotion", "tweenConfig"];
539
- var Sheet = /*#__PURE__*/forwardRef(function (_ref, ref) {
540
- var onOpenStart = _ref.onOpenStart,
541
- onOpenEnd = _ref.onOpenEnd,
542
- onClose = _ref.onClose,
543
- onCloseStart = _ref.onCloseStart,
544
- onCloseEnd = _ref.onCloseEnd,
545
- onSnap = _ref.onSnap,
546
- children = _ref.children,
547
- _ref$disableScrollLoc = _ref.disableScrollLocking,
548
- disableScrollLocking = _ref$disableScrollLoc === void 0 ? false : _ref$disableScrollLoc,
549
- isOpen = _ref.isOpen,
550
- snapPoints = _ref.snapPoints,
551
- rootId = _ref.rootId,
552
- mountPoint = _ref.mountPoint,
553
- style = _ref.style,
554
- _ref$detent = _ref.detent,
555
- detent = _ref$detent === void 0 ? 'full-height' : _ref$detent,
556
- _ref$initialSnap = _ref.initialSnap,
557
- initialSnap = _ref$initialSnap === void 0 ? 0 : _ref$initialSnap,
558
- _ref$disableDrag = _ref.disableDrag,
559
- disableDrag = _ref$disableDrag === void 0 ? false : _ref$disableDrag,
560
- _ref$prefersReducedMo = _ref.prefersReducedMotion,
561
- prefersReducedMotion = _ref$prefersReducedMo === void 0 ? false : _ref$prefersReducedMo,
562
- _ref$tweenConfig = _ref.tweenConfig,
563
- tweenConfig = _ref$tweenConfig === void 0 ? DEFAULT_TWEEN_CONFIG : _ref$tweenConfig,
564
- rest = _objectWithoutPropertiesLoose(_ref, _excluded);
565
- var sheetRef = useRef(null);
566
- var indicatorRotation = useMotionValue(0);
567
- var windowHeight = useWindowHeight();
568
- var shouldReduceMotion = useReducedMotion();
569
- var reduceMotion = Boolean(prefersReducedMotion || shouldReduceMotion);
570
- var animationOptions = _extends({
571
- type: 'tween'
572
- }, reduceMotion ? REDUCED_MOTION_TWEEN_CONFIG : tweenConfig);
573
- // NOTE: the inital value for `y` doesn't matter since it is overwritten by
574
- // the value driven by the `AnimatePresence` component when the sheet is opened
575
- // and after that it is driven by the gestures and/or snapping
576
- var y = useMotionValue(0);
577
- var zIndex = useTransform(y, function (value) {
578
- return value >= windowHeight ? -1 : 9999999;
579
- });
580
- var visibility = useTransform(y, function (value) {
581
- return value >= windowHeight ? 'hidden' : 'visible';
582
- });
583
- // Keep the callback fns up-to-date so that they can be accessed inside
584
- // the effect without including them to the dependencies array
585
- var callbacks = useRef({
586
- onOpenStart: onOpenStart,
587
- onOpenEnd: onOpenEnd,
588
- onCloseStart: onCloseStart,
589
- onCloseEnd: onCloseEnd
590
- });
591
- useIsomorphicLayoutEffect(function () {
592
- callbacks.current = {
593
- onOpenStart: onOpenStart,
594
- onOpenEnd: onOpenEnd,
595
- onCloseStart: onCloseStart,
596
- onCloseEnd: onCloseEnd
597
- };
598
- });
599
- if (snapPoints) {
600
- // Convert negative / percentage snap points to absolute values
601
- snapPoints = snapPoints.map(function (point) {
602
- // Percentage values e.g. between 0.0 and 1.0
603
- if (point > 0 && point <= 1) return Math.round(point * windowHeight);
604
- return point < 0 ? windowHeight + point : point; // negative values
605
- });
606
-
607
- console.assert(inDescendingOrder(snapPoints) || windowHeight === 0, "Snap points need to be in descending order got: [" + snapPoints + "]");
608
- }
609
- var onDrag = useEvent(function (_, _ref2) {
610
- var delta = _ref2.delta;
611
- // Update drag indicator rotation based on drag velocity
612
- var velocity = y.getVelocity();
613
- if (velocity > 0) indicatorRotation.set(10);
614
- if (velocity < 0) indicatorRotation.set(-10);
615
- // Make sure user cannot drag beyond the top of the sheet
616
- y.set(Math.max(y.get() + delta.y, 0));
617
- });
618
- var onDragEnd = useEvent(function (_, _ref3) {
619
- var velocity = _ref3.velocity;
620
- if (velocity.y > DRAG_VELOCITY_THRESHOLD) {
621
- // User flicked the sheet down
622
- onClose();
623
- } else {
624
- var sheetEl = sheetRef.current;
625
- var sheetHeight = sheetEl.getBoundingClientRect().height;
626
- var currentY = y.get();
627
- var snapTo = 0;
628
- if (snapPoints) {
629
- var snapToValues = snapPoints.map(function (p) {
630
- return sheetHeight - Math.min(p, sheetHeight);
631
- });
632
- // Allow snapping to the top of the sheet if detent is set to `content-height`
633
- if (detent === 'content-height' && !snapToValues.includes(0)) {
634
- snapToValues.unshift(0);
635
- }
636
- // Get the closest snap point
637
- snapTo = getClosest(snapToValues, currentY);
638
- } else if (currentY / sheetHeight > DRAG_CLOSE_THRESHOLD) {
639
- // Close if dragged over enough far
640
- snapTo = sheetHeight;
641
- }
642
- snapTo = validateSnapTo({
643
- snapTo: snapTo,
644
- sheetHeight: sheetHeight
645
- });
646
- // Update the spring value so that the sheet is animated to the snap point
647
- animate(y, snapTo, animationOptions);
648
- if (snapPoints && onSnap) {
649
- var snapValue = Math.abs(Math.round(snapPoints[0] - snapTo));
650
- var snapIndex = snapPoints.indexOf(getClosest(snapPoints, snapValue)); // prettier-ignore
651
- onSnap(snapIndex);
652
- }
653
- var roundedSheetHeight = Math.round(sheetHeight);
654
- var shouldClose = snapTo >= roundedSheetHeight;
655
- if (shouldClose) onClose();
656
- }
657
- // Reset indicator rotation after dragging
658
- indicatorRotation.set(0);
659
- });
660
- // Trigger onSnap callback when sheet is opened or closed
661
- useEffect(function () {
662
- if (!snapPoints || !onSnap) return;
663
- var snapIndex = isOpen ? initialSnap : snapPoints.length - 1;
664
- onSnap(snapIndex);
665
- }, [isOpen]); // eslint-disable-line
666
- useImperativeHandle(ref, function () {
667
- return {
668
- y: y,
669
- snapTo: function snapTo(snapIndex) {
670
- var sheetEl = sheetRef.current;
671
- if (snapPoints && snapPoints[snapIndex] !== undefined && sheetEl !== null) {
672
- var sheetHeight = sheetEl.getBoundingClientRect().height;
673
- var snapPoint = snapPoints[snapIndex];
674
- var snapTo = validateSnapTo({
675
- snapTo: sheetHeight - snapPoint,
676
- sheetHeight: sheetHeight
677
- });
678
- animate(y, snapTo, animationOptions);
679
- if (onSnap) onSnap(snapIndex);
680
- if (snapTo >= sheetHeight) onClose();
681
- }
682
- }
683
- };
684
- });
685
- useModalEffect(isOpen, rootId);
686
- // Framer Motion should handle body scroll locking but it's not working
687
- // properly on iOS. Scroll locking from React Aria seems to work much better.
688
- usePreventScroll({
689
- isDisabled: disableScrollLocking === true || !isOpen
690
- });
691
- var dragProps = useMemo(function () {
692
- var dragProps = {
693
- drag: 'y',
694
- dragElastic: 0,
695
- dragMomentum: false,
696
- dragPropagation: false,
697
- onDrag: onDrag,
698
- onDragEnd: onDragEnd
699
- };
700
- return disableDrag ? undefined : dragProps;
701
- }, [disableDrag]); // eslint-disable-line
702
- var context = {
703
- y: y,
704
- sheetRef: sheetRef,
705
- isOpen: isOpen,
706
- initialSnap: initialSnap,
707
- snapPoints: snapPoints,
708
- detent: detent,
709
- indicatorRotation: indicatorRotation,
710
- callbacks: callbacks,
711
- dragProps: dragProps,
712
- windowHeight: windowHeight,
713
- animationOptions: animationOptions,
714
- reduceMotion: reduceMotion,
715
- disableDrag: disableDrag
716
- };
717
- var sheet = createElement(SheetContext.Provider, {
718
- value: context
719
- }, createElement(motion.div, Object.assign({}, rest, {
720
- ref: ref,
721
- style: _extends({}, styles.wrapper, {
722
- zIndex: zIndex,
723
- visibility: visibility
724
- }, style)
725
- }), createElement(AnimatePresence, null, isOpen ? createElement(SheetScrollerContextProvider, null, Children.map(children, function (child, i) {
726
- return cloneElement(child, {
727
- key: "sheet-child-" + i
728
- });
729
- })) : null)));
730
- if (IS_SSR) return sheet;
731
- return createPortal(sheet, mountPoint != null ? mountPoint : document.body);
732
- });
733
-
734
- var _excluded$1 = ["children", "style", "className"];
735
- var SheetContainer = /*#__PURE__*/forwardRef(function (_ref, ref) {
736
- var children = _ref.children,
737
- _ref$style = _ref.style,
738
- style = _ref$style === void 0 ? {} : _ref$style,
739
- _ref$className = _ref.className,
740
- className = _ref$className === void 0 ? '' : _ref$className,
741
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$1);
742
- var _useSheetContext = useSheetContext(),
743
- y = _useSheetContext.y,
744
- isOpen = _useSheetContext.isOpen,
745
- callbacks = _useSheetContext.callbacks,
746
- snapPoints = _useSheetContext.snapPoints,
747
- _useSheetContext$init = _useSheetContext.initialSnap,
748
- initialSnap = _useSheetContext$init === void 0 ? 0 : _useSheetContext$init,
749
- sheetRef = _useSheetContext.sheetRef,
750
- windowHeight = _useSheetContext.windowHeight,
751
- detent = _useSheetContext.detent,
752
- animationOptions = _useSheetContext.animationOptions,
753
- reduceMotion = _useSheetContext.reduceMotion;
754
- var _useEventCallbacks = useEventCallbacks(isOpen, callbacks),
755
- handleAnimationComplete = _useEventCallbacks.handleAnimationComplete;
756
- var initialY = snapPoints ? snapPoints[0] - snapPoints[initialSnap] : 0;
757
- var maxSnapHeight = snapPoints ? snapPoints[0] : null;
758
- var height = maxSnapHeight !== null ? "min(" + maxSnapHeight + "px, " + MAX_HEIGHT + ")" : MAX_HEIGHT;
759
- return createElement(motion.div, Object.assign({}, rest, {
760
- ref: mergeRefs([sheetRef, ref]),
761
- className: "react-modal-sheet-container " + className,
762
- style: _extends({}, styles.container, style, detent === 'full-height' && {
763
- height: height
764
- }, detent === 'content-height' && {
765
- maxHeight: height
766
- }, {
767
- y: y
768
- }),
769
- initial: reduceMotion ? false : {
770
- y: windowHeight
771
- },
772
- animate: {
773
- y: initialY,
774
- transition: animationOptions
775
- },
776
- exit: {
777
- y: windowHeight,
778
- transition: animationOptions
779
- },
780
- onAnimationComplete: handleAnimationComplete
781
- }), children);
782
- });
783
-
784
- var _excluded$2 = ["children", "style", "disableDrag", "className"];
785
- var SheetContent = /*#__PURE__*/forwardRef(function (_ref, ref) {
786
- var children = _ref.children,
787
- style = _ref.style,
788
- disableDrag = _ref.disableDrag,
789
- _ref$className = _ref.className,
790
- className = _ref$className === void 0 ? '' : _ref$className,
791
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$2);
792
- var sheetContext = useSheetContext();
793
- var sheetScrollerContext = useSheetScrollerContext();
794
- var _useDragConstraints = useDragConstraints(),
795
- constraintsRef = _useDragConstraints.constraintsRef,
796
- onMeasureDragConstraints = _useDragConstraints.onMeasureDragConstraints;
797
- var dragProps = disableDrag || sheetScrollerContext.disableDrag ? undefined : sheetContext.dragProps;
798
- return createElement(motion.div, Object.assign({}, rest, {
799
- ref: mergeRefs([ref, constraintsRef]),
800
- className: "react-modal-sheet-content " + className,
801
- style: _extends({}, styles.content, style)
802
- }, dragProps, {
803
- dragConstraints: constraintsRef,
804
- onMeasureDragConstraints: onMeasureDragConstraints
805
- }), children);
806
- });
807
-
808
- var _excluded$3 = ["children", "style", "disableDrag"];
809
- var SheetHeader = /*#__PURE__*/forwardRef(function (_ref, ref) {
810
- var children = _ref.children,
811
- style = _ref.style,
812
- disableDrag = _ref.disableDrag,
813
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$3);
814
- var _useSheetContext = useSheetContext(),
815
- indicatorRotation = _useSheetContext.indicatorRotation,
816
- dragProps = _useSheetContext.dragProps;
817
- var _useDragConstraints = useDragConstraints(),
818
- constraintsRef = _useDragConstraints.constraintsRef,
819
- onMeasureDragConstraints = _useDragConstraints.onMeasureDragConstraints;
820
- var _dragProps = disableDrag ? undefined : dragProps;
821
- var indicator1Transform = useTransform(indicatorRotation, function (r) {
822
- return "translateX(2px) rotate(" + r + "deg)";
823
- });
824
- var indicator2Transform = useTransform(indicatorRotation, function (r) {
825
- return "translateX(-2px) rotate(" + -1 * r + "deg)";
826
- });
827
- return createElement(motion.div, Object.assign({}, rest, {
828
- ref: mergeRefs([ref, constraintsRef]),
829
- style: _extends({}, styles.headerWrapper, style)
830
- }, _dragProps, {
831
- dragConstraints: constraintsRef,
832
- onMeasureDragConstraints: onMeasureDragConstraints
833
- }), children || createElement("div", {
834
- className: "react-modal-sheet-header",
835
- style: styles.header
836
- }, createElement(motion.span, {
837
- className: "react-modal-sheet-drag-indicator",
838
- style: _extends({}, styles.indicator, {
839
- transform: indicator1Transform
840
- })
841
- }), createElement(motion.span, {
842
- className: "react-modal-sheet-drag-indicator",
843
- style: _extends({}, styles.indicator, {
844
- transform: indicator2Transform
845
- })
846
- })));
847
- });
848
-
849
- var _excluded$4 = ["style", "className"];
850
- var isClickable = function isClickable(props) {
851
- return !!props.onClick || !!props.onTap;
852
- };
853
- var SheetBackdrop = /*#__PURE__*/forwardRef(function (_ref, ref) {
854
- var _ref$style = _ref.style,
855
- style = _ref$style === void 0 ? {} : _ref$style,
856
- _ref$className = _ref.className,
857
- className = _ref$className === void 0 ? '' : _ref$className,
858
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$4);
859
- var Comp = isClickable(rest) ? motion.button : motion.div;
860
- var pointerEvents = isClickable(rest) ? 'auto' : 'none';
861
- return createElement(Comp, Object.assign({}, rest, {
862
- ref: ref,
863
- className: "react-modal-sheet-backdrop " + className,
864
- style: _extends({}, styles.backdrop, style, {
865
- pointerEvents: pointerEvents
866
- }),
867
- initial: {
868
- opacity: 0
869
- },
870
- animate: {
871
- opacity: 1
872
- },
873
- exit: {
874
- opacity: 0
875
- }
876
- }));
877
- });
878
-
879
- var _excluded$5 = ["draggableAt", "children", "style", "className"];
880
- var SheetScroller = /*#__PURE__*/forwardRef(function (_ref, ref) {
881
- var _ref$draggableAt = _ref.draggableAt,
882
- draggableAt = _ref$draggableAt === void 0 ? 'top' : _ref$draggableAt,
883
- children = _ref.children,
884
- style = _ref.style,
885
- _ref$className = _ref.className,
886
- className = _ref$className === void 0 ? '' : _ref$className,
887
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$5);
888
- var sheetScrollerContext = useSheetScrollerContext();
889
- function determineDragState(element) {
890
- var scrollTop = element.scrollTop,
891
- scrollHeight = element.scrollHeight,
892
- clientHeight = element.clientHeight;
893
- var isScrollable = scrollHeight > clientHeight;
894
- if (!isScrollable) return;
895
- var isAtTop = scrollTop <= 0;
896
- var isAtBottom = scrollHeight - scrollTop === clientHeight;
897
- var shouldEnable = draggableAt === 'top' && isAtTop || draggableAt === 'bottom' && isAtBottom || draggableAt === 'both' && (isAtTop || isAtBottom);
898
- if (shouldEnable) {
899
- sheetScrollerContext.setDragEnabled();
900
- } else {
901
- sheetScrollerContext.setDragDisabled();
902
- }
903
- }
904
- function onScroll(e) {
905
- determineDragState(e.currentTarget);
906
- }
907
- function onTouchStart(e) {
908
- determineDragState(e.currentTarget);
909
- }
910
- var scrollProps = isTouchDevice() ? {
911
- onScroll: onScroll,
912
- onTouchStart: onTouchStart
913
- } : undefined;
914
- return createElement("div", Object.assign({}, rest, {
915
- ref: ref,
916
- className: "react-modal-sheet-scroller " + className,
917
- style: _extends({}, styles.scroller, style)
918
- }, scrollProps), children);
919
- });
920
-
921
- // HACK: this is needed to get the typing to work properly...
922
- var _SheetCompound = Sheet;
923
- _SheetCompound.Container = SheetContainer;
924
- _SheetCompound.Header = SheetHeader;
925
- _SheetCompound.Content = SheetContent;
926
- _SheetCompound.Backdrop = SheetBackdrop;
927
- _SheetCompound.Scroller = SheetScroller;
928
-
929
- export default _SheetCompound;
930
- //# sourceMappingURL=react-modal-sheet.esm.js.map