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