react-modal-sheet 2.2.1 → 3.1.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,940 +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
- // In special situations, `onTouchStart` may be called without `onTouchStart` being called.
346
- // (e.g. when the user places a finger on the screen before the <Sheet> is mounted and then moves the finger after it is mounted).
347
- // If `onTouchStart` is not called, `scrollable` is `undefined`. Therefore, such cases are ignored.
348
- if (scrollable === undefined) {
349
- return;
350
- }
351
- // Prevent scrolling the window.
352
- if (scrollable === document.documentElement || scrollable === document.body) {
353
- e.preventDefault();
354
- return;
355
- }
356
- // Prevent scrolling up when at the top and scrolling down when at the bottom
357
- // of a nested scrollable area, otherwise mobile Safari will start scrolling
358
- // the window instead. Unfortunately, this disables bounce scrolling when at
359
- // the top but it's the best we can do.
360
- var y = e.changedTouches[0].pageY;
361
- var scrollTop = scrollable.scrollTop;
362
- var bottom = scrollable.scrollHeight - scrollable.clientHeight;
363
- // Fix for: https://github.com/adobe/react-spectrum/pull/3780/files
364
- if (bottom === 0) {
365
- return;
366
- }
367
- if (scrollTop <= 0 && y > lastY || scrollTop >= bottom && y < lastY) {
368
- e.preventDefault();
369
- }
370
- lastY = y;
371
- };
372
- var onTouchEnd = function onTouchEnd(e) {
373
- var target = e.target;
374
- // Apply this change if we're not already focused on the target element
375
- if (willOpenKeyboard(target) && target !== document.activeElement) {
376
- e.preventDefault();
377
- // Apply a transform to trick Safari into thinking the input is at the top of the page
378
- // so it doesn't try to scroll it into view. When tapping on an input, this needs to
379
- // be done before the "focus" event, so we have to focus the element ourselves.
380
- target.style.transform = 'translateY(-2000px)';
381
- target.focus();
382
- requestAnimationFrame(function () {
383
- target.style.transform = '';
384
- });
385
- }
386
- };
387
- var onFocus = function onFocus(e) {
388
- var target = e.target;
389
- if (willOpenKeyboard(target)) {
390
- // Transform also needs to be applied in the focus event in cases where focus moves
391
- // other than tapping on an input directly, e.g. the next/previous buttons in the
392
- // software keyboard. In these cases, it seems applying the transform in the focus event
393
- // is good enough, whereas when tapping an input, it must be done before the focus event. 🤷‍♂️
394
- target.style.transform = 'translateY(-2000px)';
395
- requestAnimationFrame(function () {
396
- target.style.transform = '';
397
- // This will have prevented the browser from scrolling the focused element into view,
398
- // so we need to do this ourselves in a way that doesn't cause the whole page to scroll.
399
- if (visualViewport) {
400
- if (visualViewport.height < window.innerHeight) {
401
- // If the keyboard is already visible, do this after one additional frame
402
- // to wait for the transform to be removed.
403
- requestAnimationFrame(function () {
404
- scrollIntoView(target);
405
- });
406
- } else {
407
- // Otherwise, wait for the visual viewport to resize before scrolling so we can
408
- // measure the correct position to scroll to.
409
- visualViewport.addEventListener('resize', function () {
410
- return scrollIntoView(target);
411
- }, {
412
- once: true
413
- });
414
- }
415
- }
416
- });
417
- }
418
- };
419
- var onWindowScroll = function onWindowScroll() {
420
- // Last resort. If the window scrolled, scroll it back to the top.
421
- // It should always be at the top because the body will have a negative margin (see below).
422
- window.scrollTo(0, 0);
423
- };
424
- // Record the original scroll position so we can restore it.
425
- // Then apply a negative margin to the body to offset it by the scroll position. This will
426
- // enable us to scroll the window to the top, which is required for the rest of this to work.
427
- var scrollX = window.pageXOffset;
428
- var scrollY = window.pageYOffset;
429
- 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"));
430
- // Scroll to the top. The negative margin on the body will make this appear the same.
431
- window.scrollTo(0, 0);
432
- var removeEvents = utils.chain(addEvent(document, 'touchstart', onTouchStart, {
433
- passive: false,
434
- capture: true
435
- }), addEvent(document, 'touchmove', onTouchMove, {
436
- passive: false,
437
- capture: true
438
- }), addEvent(document, 'touchend', onTouchEnd, {
439
- passive: false,
440
- capture: true
441
- }), addEvent(document, 'focus', onFocus, true), addEvent(window, 'scroll', onWindowScroll));
442
- return function () {
443
- // Restore styles and scroll the page back to where it was.
444
- restoreStyles();
445
- removeEvents();
446
- window.scrollTo(scrollX, scrollY);
447
- };
448
- }
449
- // Sets a CSS property on an element, and returns a function to revert it to the previous value.
450
- function setStyle(element, style, value) {
451
- var cur = element.style[style];
452
- element.style[style] = value;
453
- return function () {
454
- element.style[style] = cur;
455
- };
456
- }
457
- // Adds an event listener to an element, and returns a function to remove it.
458
- function addEvent(target, event, handler, options) {
459
- target.addEventListener(event, handler, options);
460
- return function () {
461
- target.removeEventListener(event, handler, options);
462
- };
463
- }
464
- function scrollIntoView(target) {
465
- var root = document.scrollingElement || document.documentElement;
466
- while (target && target !== root) {
467
- // Find the parent scrollable element and adjust the scroll position if the target is not already in view.
468
- var scrollable = utils.getScrollParent(target);
469
- if (scrollable !== document.documentElement && scrollable !== document.body && scrollable !== target) {
470
- var scrollableTop = scrollable.getBoundingClientRect().top;
471
- var targetTop = target.getBoundingClientRect().top;
472
- if (targetTop > scrollableTop + target.clientHeight) {
473
- scrollable.scrollTop += targetTop - scrollableTop;
474
- }
475
- }
476
- target = scrollable.parentElement;
477
- }
478
- }
479
- function willOpenKeyboard(target) {
480
- return target instanceof HTMLInputElement && !nonTextInputTypes.has(target.type) || target instanceof HTMLTextAreaElement || target instanceof HTMLElement && target.isContentEditable;
481
- }
482
-
483
- var styles = {
484
- wrapper: {
485
- position: 'fixed',
486
- top: 0,
487
- bottom: 0,
488
- left: 0,
489
- right: 0,
490
- overflow: 'hidden',
491
- pointerEvents: 'none'
492
- },
493
- backdrop: {
494
- zIndex: 1,
495
- position: 'fixed',
496
- top: 0,
497
- left: 0,
498
- width: '100%',
499
- height: '100%',
500
- backgroundColor: 'rgba(0, 0, 0, 0.2)',
501
- touchAction: 'none',
502
- border: 'none'
503
- },
504
- container: {
505
- zIndex: 2,
506
- position: 'absolute',
507
- left: 0,
508
- bottom: 0,
509
- width: '100%',
510
- backgroundColor: '#fff',
511
- borderTopRightRadius: '8px',
512
- borderTopLeftRadius: '8px',
513
- boxShadow: '0px -2px 16px rgba(0, 0, 0, 0.3)',
514
- display: 'flex',
515
- flexDirection: 'column',
516
- pointerEvents: 'auto'
517
- },
518
- headerWrapper: {
519
- width: '100%'
520
- },
521
- header: {
522
- height: '40px',
523
- width: '100%',
524
- position: 'relative',
525
- display: 'flex',
526
- alignItems: 'center',
527
- justifyContent: 'center'
528
- },
529
- indicator: {
530
- width: '18px',
531
- height: '4px',
532
- borderRadius: '99px',
533
- backgroundColor: '#ddd'
534
- },
535
- content: {
536
- flexGrow: 1,
537
- display: 'flex',
538
- flexDirection: 'column',
539
- minHeight: '0px',
540
- position: 'relative'
541
- },
542
- scroller: {
543
- height: '100%',
544
- overflowY: 'auto'
545
- }
546
- };
547
-
548
- var _excluded = ["onOpenStart", "onOpenEnd", "onClose", "onCloseStart", "onCloseEnd", "onSnap", "children", "disableScrollLocking", "isOpen", "snapPoints", "rootId", "mountPoint", "style", "detent", "initialSnap", "disableDrag", "prefersReducedMotion", "tweenConfig"];
549
- var Sheet = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
550
- var onOpenStart = _ref.onOpenStart,
551
- onOpenEnd = _ref.onOpenEnd,
552
- onClose = _ref.onClose,
553
- onCloseStart = _ref.onCloseStart,
554
- onCloseEnd = _ref.onCloseEnd,
555
- onSnap = _ref.onSnap,
556
- children = _ref.children,
557
- _ref$disableScrollLoc = _ref.disableScrollLocking,
558
- disableScrollLocking = _ref$disableScrollLoc === void 0 ? false : _ref$disableScrollLoc,
559
- isOpen = _ref.isOpen,
560
- snapPoints = _ref.snapPoints,
561
- rootId = _ref.rootId,
562
- mountPoint = _ref.mountPoint,
563
- style = _ref.style,
564
- _ref$detent = _ref.detent,
565
- detent = _ref$detent === void 0 ? 'full-height' : _ref$detent,
566
- _ref$initialSnap = _ref.initialSnap,
567
- initialSnap = _ref$initialSnap === void 0 ? 0 : _ref$initialSnap,
568
- _ref$disableDrag = _ref.disableDrag,
569
- disableDrag = _ref$disableDrag === void 0 ? false : _ref$disableDrag,
570
- _ref$prefersReducedMo = _ref.prefersReducedMotion,
571
- prefersReducedMotion = _ref$prefersReducedMo === void 0 ? false : _ref$prefersReducedMo,
572
- _ref$tweenConfig = _ref.tweenConfig,
573
- tweenConfig = _ref$tweenConfig === void 0 ? DEFAULT_TWEEN_CONFIG : _ref$tweenConfig,
574
- rest = _objectWithoutPropertiesLoose(_ref, _excluded);
575
- var sheetRef = React.useRef(null);
576
- var indicatorRotation = framerMotion.useMotionValue(0);
577
- var windowHeight = useWindowHeight();
578
- var shouldReduceMotion = framerMotion.useReducedMotion();
579
- var reduceMotion = Boolean(prefersReducedMotion || shouldReduceMotion);
580
- var animationOptions = _extends({
581
- type: 'tween'
582
- }, reduceMotion ? REDUCED_MOTION_TWEEN_CONFIG : tweenConfig);
583
- // NOTE: the inital value for `y` doesn't matter since it is overwritten by
584
- // the value driven by the `AnimatePresence` component when the sheet is opened
585
- // and after that it is driven by the gestures and/or snapping
586
- var y = framerMotion.useMotionValue(0);
587
- var zIndex = framerMotion.useTransform(y, function (value) {
588
- return value >= windowHeight ? -1 : 9999999;
589
- });
590
- var visibility = framerMotion.useTransform(y, function (value) {
591
- return value >= windowHeight ? 'hidden' : 'visible';
592
- });
593
- // Keep the callback fns up-to-date so that they can be accessed inside
594
- // the effect without including them to the dependencies array
595
- var callbacks = React.useRef({
596
- onOpenStart: onOpenStart,
597
- onOpenEnd: onOpenEnd,
598
- onCloseStart: onCloseStart,
599
- onCloseEnd: onCloseEnd
600
- });
601
- useIsomorphicLayoutEffect(function () {
602
- callbacks.current = {
603
- onOpenStart: onOpenStart,
604
- onOpenEnd: onOpenEnd,
605
- onCloseStart: onCloseStart,
606
- onCloseEnd: onCloseEnd
607
- };
608
- });
609
- if (snapPoints) {
610
- // Convert negative / percentage snap points to absolute values
611
- snapPoints = snapPoints.map(function (point) {
612
- // Percentage values e.g. between 0.0 and 1.0
613
- if (point > 0 && point <= 1) return Math.round(point * windowHeight);
614
- return point < 0 ? windowHeight + point : point; // negative values
615
- });
616
-
617
- console.assert(inDescendingOrder(snapPoints) || windowHeight === 0, "Snap points need to be in descending order got: [" + snapPoints + "]");
618
- }
619
- var onDrag = useEvent(function (_, _ref2) {
620
- var delta = _ref2.delta;
621
- // Update drag indicator rotation based on drag velocity
622
- var velocity = y.getVelocity();
623
- if (velocity > 0) indicatorRotation.set(10);
624
- if (velocity < 0) indicatorRotation.set(-10);
625
- // Make sure user cannot drag beyond the top of the sheet
626
- y.set(Math.max(y.get() + delta.y, 0));
627
- });
628
- var onDragEnd = useEvent(function (_, _ref3) {
629
- var velocity = _ref3.velocity;
630
- if (velocity.y > DRAG_VELOCITY_THRESHOLD) {
631
- // User flicked the sheet down
632
- onClose();
633
- } else {
634
- var sheetEl = sheetRef.current;
635
- var sheetHeight = sheetEl.getBoundingClientRect().height;
636
- var currentY = y.get();
637
- var snapTo = 0;
638
- if (snapPoints) {
639
- var snapToValues = snapPoints.map(function (p) {
640
- return sheetHeight - Math.min(p, sheetHeight);
641
- });
642
- // Allow snapping to the top of the sheet if detent is set to `content-height`
643
- if (detent === 'content-height' && !snapToValues.includes(0)) {
644
- snapToValues.unshift(0);
645
- }
646
- // Get the closest snap point
647
- snapTo = getClosest(snapToValues, currentY);
648
- } else if (currentY / sheetHeight > DRAG_CLOSE_THRESHOLD) {
649
- // Close if dragged over enough far
650
- snapTo = sheetHeight;
651
- }
652
- snapTo = validateSnapTo({
653
- snapTo: snapTo,
654
- sheetHeight: sheetHeight
655
- });
656
- // Update the spring value so that the sheet is animated to the snap point
657
- framerMotion.animate(y, snapTo, animationOptions);
658
- if (snapPoints && onSnap) {
659
- var snapValue = Math.abs(Math.round(snapPoints[0] - snapTo));
660
- var snapIndex = snapPoints.indexOf(getClosest(snapPoints, snapValue)); // prettier-ignore
661
- onSnap(snapIndex);
662
- }
663
- var roundedSheetHeight = Math.round(sheetHeight);
664
- var shouldClose = snapTo >= roundedSheetHeight;
665
- if (shouldClose) onClose();
666
- }
667
- // Reset indicator rotation after dragging
668
- indicatorRotation.set(0);
669
- });
670
- // Trigger onSnap callback when sheet is opened or closed
671
- React.useEffect(function () {
672
- if (!snapPoints || !onSnap) return;
673
- var snapIndex = isOpen ? initialSnap : snapPoints.length - 1;
674
- onSnap(snapIndex);
675
- }, [isOpen]); // eslint-disable-line
676
- React.useImperativeHandle(ref, function () {
677
- return {
678
- y: y,
679
- snapTo: function snapTo(snapIndex) {
680
- var sheetEl = sheetRef.current;
681
- if (snapPoints && snapPoints[snapIndex] !== undefined && sheetEl !== null) {
682
- var sheetHeight = sheetEl.getBoundingClientRect().height;
683
- var snapPoint = snapPoints[snapIndex];
684
- var snapTo = validateSnapTo({
685
- snapTo: sheetHeight - snapPoint,
686
- sheetHeight: sheetHeight
687
- });
688
- framerMotion.animate(y, snapTo, animationOptions);
689
- if (onSnap) onSnap(snapIndex);
690
- if (snapTo >= sheetHeight) onClose();
691
- }
692
- }
693
- };
694
- });
695
- useModalEffect(isOpen, rootId);
696
- // Framer Motion should handle body scroll locking but it's not working
697
- // properly on iOS. Scroll locking from React Aria seems to work much better.
698
- usePreventScroll({
699
- isDisabled: disableScrollLocking === true || !isOpen
700
- });
701
- var dragProps = React.useMemo(function () {
702
- var dragProps = {
703
- drag: 'y',
704
- dragElastic: 0,
705
- dragMomentum: false,
706
- dragPropagation: false,
707
- onDrag: onDrag,
708
- onDragEnd: onDragEnd
709
- };
710
- return disableDrag ? undefined : dragProps;
711
- }, [disableDrag]); // eslint-disable-line
712
- var context = {
713
- y: y,
714
- sheetRef: sheetRef,
715
- isOpen: isOpen,
716
- initialSnap: initialSnap,
717
- snapPoints: snapPoints,
718
- detent: detent,
719
- indicatorRotation: indicatorRotation,
720
- callbacks: callbacks,
721
- dragProps: dragProps,
722
- windowHeight: windowHeight,
723
- animationOptions: animationOptions,
724
- reduceMotion: reduceMotion,
725
- disableDrag: disableDrag
726
- };
727
- var sheet = React.createElement(SheetContext.Provider, {
728
- value: context
729
- }, React.createElement(framerMotion.motion.div, Object.assign({}, rest, {
730
- ref: ref,
731
- style: _extends({}, styles.wrapper, {
732
- zIndex: zIndex,
733
- visibility: visibility
734
- }, style)
735
- }), React.createElement(framerMotion.AnimatePresence, null, isOpen ? React.createElement(SheetScrollerContextProvider, null, React.Children.map(children, function (child, i) {
736
- return React.cloneElement(child, {
737
- key: "sheet-child-" + i
738
- });
739
- })) : null)));
740
- if (IS_SSR) return sheet;
741
- return ReactDOM.createPortal(sheet, mountPoint != null ? mountPoint : document.body);
742
- });
743
-
744
- var _excluded$1 = ["children", "style", "className"];
745
- var SheetContainer = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
746
- var children = _ref.children,
747
- _ref$style = _ref.style,
748
- style = _ref$style === void 0 ? {} : _ref$style,
749
- _ref$className = _ref.className,
750
- className = _ref$className === void 0 ? '' : _ref$className,
751
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$1);
752
- var _useSheetContext = useSheetContext(),
753
- y = _useSheetContext.y,
754
- isOpen = _useSheetContext.isOpen,
755
- callbacks = _useSheetContext.callbacks,
756
- snapPoints = _useSheetContext.snapPoints,
757
- _useSheetContext$init = _useSheetContext.initialSnap,
758
- initialSnap = _useSheetContext$init === void 0 ? 0 : _useSheetContext$init,
759
- sheetRef = _useSheetContext.sheetRef,
760
- windowHeight = _useSheetContext.windowHeight,
761
- detent = _useSheetContext.detent,
762
- animationOptions = _useSheetContext.animationOptions,
763
- reduceMotion = _useSheetContext.reduceMotion;
764
- var _useEventCallbacks = useEventCallbacks(isOpen, callbacks),
765
- handleAnimationComplete = _useEventCallbacks.handleAnimationComplete;
766
- var initialY = snapPoints ? snapPoints[0] - snapPoints[initialSnap] : 0;
767
- var maxSnapHeight = snapPoints ? snapPoints[0] : null;
768
- var height = maxSnapHeight !== null ? "min(" + maxSnapHeight + "px, " + MAX_HEIGHT + ")" : MAX_HEIGHT;
769
- return React.createElement(framerMotion.motion.div, Object.assign({}, rest, {
770
- ref: mergeRefs([sheetRef, ref]),
771
- className: "react-modal-sheet-container " + className,
772
- style: _extends({}, styles.container, style, detent === 'full-height' && {
773
- height: height
774
- }, detent === 'content-height' && {
775
- maxHeight: height
776
- }, {
777
- y: y
778
- }),
779
- initial: reduceMotion ? false : {
780
- y: windowHeight
781
- },
782
- animate: {
783
- y: initialY,
784
- transition: animationOptions
785
- },
786
- exit: {
787
- y: windowHeight,
788
- transition: animationOptions
789
- },
790
- onAnimationComplete: handleAnimationComplete
791
- }), children);
792
- });
793
-
794
- var _excluded$2 = ["children", "style", "disableDrag", "className"];
795
- var SheetContent = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
796
- var children = _ref.children,
797
- style = _ref.style,
798
- disableDrag = _ref.disableDrag,
799
- _ref$className = _ref.className,
800
- className = _ref$className === void 0 ? '' : _ref$className,
801
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$2);
802
- var sheetContext = useSheetContext();
803
- var sheetScrollerContext = useSheetScrollerContext();
804
- var _useDragConstraints = useDragConstraints(),
805
- constraintsRef = _useDragConstraints.constraintsRef,
806
- onMeasureDragConstraints = _useDragConstraints.onMeasureDragConstraints;
807
- var dragProps = disableDrag || sheetScrollerContext.disableDrag ? undefined : sheetContext.dragProps;
808
- return React.createElement(framerMotion.motion.div, Object.assign({}, rest, {
809
- ref: mergeRefs([ref, constraintsRef]),
810
- className: "react-modal-sheet-content " + className,
811
- style: _extends({}, styles.content, style)
812
- }, dragProps, {
813
- dragConstraints: constraintsRef,
814
- onMeasureDragConstraints: onMeasureDragConstraints
815
- }), children);
816
- });
817
-
818
- var _excluded$3 = ["children", "style", "disableDrag"];
819
- var SheetHeader = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
820
- var children = _ref.children,
821
- style = _ref.style,
822
- disableDrag = _ref.disableDrag,
823
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$3);
824
- var _useSheetContext = useSheetContext(),
825
- indicatorRotation = _useSheetContext.indicatorRotation,
826
- dragProps = _useSheetContext.dragProps;
827
- var _useDragConstraints = useDragConstraints(),
828
- constraintsRef = _useDragConstraints.constraintsRef,
829
- onMeasureDragConstraints = _useDragConstraints.onMeasureDragConstraints;
830
- var _dragProps = disableDrag ? undefined : dragProps;
831
- var indicator1Transform = framerMotion.useTransform(indicatorRotation, function (r) {
832
- return "translateX(2px) rotate(" + r + "deg)";
833
- });
834
- var indicator2Transform = framerMotion.useTransform(indicatorRotation, function (r) {
835
- return "translateX(-2px) rotate(" + -1 * r + "deg)";
836
- });
837
- return React.createElement(framerMotion.motion.div, Object.assign({}, rest, {
838
- ref: mergeRefs([ref, constraintsRef]),
839
- style: _extends({}, styles.headerWrapper, style)
840
- }, _dragProps, {
841
- dragConstraints: constraintsRef,
842
- onMeasureDragConstraints: onMeasureDragConstraints
843
- }), children || React.createElement("div", {
844
- className: "react-modal-sheet-header",
845
- style: styles.header
846
- }, React.createElement(framerMotion.motion.span, {
847
- className: "react-modal-sheet-drag-indicator",
848
- style: _extends({}, styles.indicator, {
849
- transform: indicator1Transform
850
- })
851
- }), React.createElement(framerMotion.motion.span, {
852
- className: "react-modal-sheet-drag-indicator",
853
- style: _extends({}, styles.indicator, {
854
- transform: indicator2Transform
855
- })
856
- })));
857
- });
858
-
859
- var _excluded$4 = ["style", "className"];
860
- var isClickable = function isClickable(props) {
861
- return !!props.onClick || !!props.onTap;
862
- };
863
- var SheetBackdrop = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
864
- var _ref$style = _ref.style,
865
- style = _ref$style === void 0 ? {} : _ref$style,
866
- _ref$className = _ref.className,
867
- className = _ref$className === void 0 ? '' : _ref$className,
868
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$4);
869
- var Comp = isClickable(rest) ? framerMotion.motion.button : framerMotion.motion.div;
870
- var pointerEvents = isClickable(rest) ? 'auto' : 'none';
871
- return React.createElement(Comp, Object.assign({}, rest, {
872
- ref: ref,
873
- className: "react-modal-sheet-backdrop " + className,
874
- style: _extends({}, styles.backdrop, style, {
875
- pointerEvents: pointerEvents
876
- }),
877
- initial: {
878
- opacity: 0
879
- },
880
- animate: {
881
- opacity: 1
882
- },
883
- exit: {
884
- opacity: 0
885
- }
886
- }));
887
- });
888
-
889
- var _excluded$5 = ["draggableAt", "children", "style", "className"];
890
- var SheetScroller = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
891
- var _ref$draggableAt = _ref.draggableAt,
892
- draggableAt = _ref$draggableAt === void 0 ? 'top' : _ref$draggableAt,
893
- children = _ref.children,
894
- style = _ref.style,
895
- _ref$className = _ref.className,
896
- className = _ref$className === void 0 ? '' : _ref$className,
897
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$5);
898
- var sheetScrollerContext = useSheetScrollerContext();
899
- function determineDragState(element) {
900
- var scrollTop = element.scrollTop,
901
- scrollHeight = element.scrollHeight,
902
- clientHeight = element.clientHeight;
903
- var isScrollable = scrollHeight > clientHeight;
904
- if (!isScrollable) return;
905
- var isAtTop = scrollTop <= 0;
906
- var isAtBottom = scrollHeight - scrollTop === clientHeight;
907
- var shouldEnable = draggableAt === 'top' && isAtTop || draggableAt === 'bottom' && isAtBottom || draggableAt === 'both' && (isAtTop || isAtBottom);
908
- if (shouldEnable) {
909
- sheetScrollerContext.setDragEnabled();
910
- } else {
911
- sheetScrollerContext.setDragDisabled();
912
- }
913
- }
914
- function onScroll(e) {
915
- determineDragState(e.currentTarget);
916
- }
917
- function onTouchStart(e) {
918
- determineDragState(e.currentTarget);
919
- }
920
- var scrollProps = isTouchDevice() ? {
921
- onScroll: onScroll,
922
- onTouchStart: onTouchStart
923
- } : undefined;
924
- return React.createElement("div", Object.assign({}, rest, {
925
- ref: ref,
926
- className: "react-modal-sheet-scroller " + className,
927
- style: _extends({}, styles.scroller, style)
928
- }, scrollProps), children);
929
- });
930
-
931
- // HACK: this is needed to get the typing to work properly...
932
- var _SheetCompound = Sheet;
933
- _SheetCompound.Container = SheetContainer;
934
- _SheetCompound.Header = SheetHeader;
935
- _SheetCompound.Content = SheetContent;
936
- _SheetCompound.Backdrop = SheetBackdrop;
937
- _SheetCompound.Scroller = SheetScroller;
938
-
939
- exports.default = _SheetCompound;
940
- //# sourceMappingURL=react-modal-sheet.cjs.development.js.map