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