@seed-design/react-drawer 1.0.2 → 1.0.4

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.
@@ -5,7 +5,7 @@ import * as DialogPrimitive from '@radix-ui/react-dialog';
5
5
  import { useCallbackRef } from '@radix-ui/react-use-callback-ref';
6
6
  import { dataAttr } from '@seed-design/dom-utils';
7
7
  import { Primitive } from '@seed-design/react-primitive';
8
- import React, { useLayoutEffect, useEffect, useState, useRef, useCallback, useMemo, createContext, useContext, forwardRef } from 'react';
8
+ import React, { useState, useRef, useCallback, useEffect, useMemo, createContext, useContext, forwardRef } from 'react';
9
9
  import { useControllableState } from '@radix-ui/react-use-controllable-state';
10
10
 
11
11
  function isMobileFirefox() {
@@ -49,6 +49,21 @@ const WINDOW_TOP_OFFSET = 26;
49
49
  const DRAG_CLASS = "seed-dragging";
50
50
 
51
51
  const cache = new WeakMap();
52
+ // HTML input types that do not cause the software keyboard to appear.
53
+ const nonTextInputTypes = new Set([
54
+ "checkbox",
55
+ "radio",
56
+ "range",
57
+ "color",
58
+ "file",
59
+ "image",
60
+ "button",
61
+ "submit",
62
+ "reset"
63
+ ]);
64
+ function isInput(target) {
65
+ return target instanceof HTMLInputElement && !nonTextInputTypes.has(target.type) || target instanceof HTMLTextAreaElement || target instanceof HTMLElement && target.isContentEditable;
66
+ }
52
67
  function set(el, styles, ignoreCache = false) {
53
68
  if (!el || !(el instanceof HTMLElement)) return;
54
69
  let originalStyles = {};
@@ -223,255 +238,10 @@ let previousBodyPosition = null;
223
238
  };
224
239
  }
225
240
 
226
- // This code comes from https://github.com/adobe/react-spectrum/blob/main/packages/%40react-aria/overlays/src/usePreventScroll.ts
227
- const KEYBOARD_BUFFER = 24;
228
- const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
229
- function chain(...callbacks) {
230
- return (...args)=>{
231
- for (let callback of callbacks){
232
- if (typeof callback === "function") {
233
- callback(...args);
234
- }
235
- }
236
- };
237
- }
238
- // @ts-ignore
239
- const visualViewport = typeof document !== "undefined" && window.visualViewport;
240
- function isScrollable(node) {
241
- let style = window.getComputedStyle(node);
242
- return /(auto|scroll)/.test(style.overflow + style.overflowX + style.overflowY);
243
- }
244
- function getScrollParent(node) {
245
- if (isScrollable(node)) {
246
- node = node.parentElement;
247
- }
248
- while(node && !isScrollable(node)){
249
- node = node.parentElement;
250
- }
251
- return node || document.scrollingElement || document.documentElement;
252
- }
253
- // HTML input types that do not cause the software keyboard to appear.
254
- const nonTextInputTypes = new Set([
255
- "checkbox",
256
- "radio",
257
- "range",
258
- "color",
259
- "file",
260
- "image",
261
- "button",
262
- "submit",
263
- "reset"
264
- ]);
265
- // The number of active usePreventScroll calls. Used to determine whether to revert back to the original page style/scroll position
266
- let preventScrollCount = 0;
267
- let restore;
268
- /**
269
- * Prevents scrolling on the document body on mount, and
270
- * restores it on unmount. Also ensures that content does not
271
- * shift due to the scrollbars disappearing.
272
- */ function usePreventScroll(options = {}) {
273
- let { isDisabled } = options;
274
- useIsomorphicLayoutEffect(()=>{
275
- if (isDisabled) {
276
- return;
277
- }
278
- preventScrollCount++;
279
- if (preventScrollCount === 1) {
280
- if (isIOS()) {
281
- restore = preventScrollMobileSafari();
282
- }
283
- }
284
- return ()=>{
285
- preventScrollCount--;
286
- if (preventScrollCount === 0) {
287
- restore?.();
288
- }
289
- };
290
- }, [
291
- isDisabled
292
- ]);
293
- }
294
- // Mobile Safari is a whole different beast. Even with overflow: hidden,
295
- // it still scrolls the page in many situations:
296
- //
297
- // 1. When the bottom toolbar and address bar are collapsed, page scrolling is always allowed.
298
- // 2. When the keyboard is visible, the viewport does not resize. Instead, the keyboard covers part of
299
- // it, so it becomes scrollable.
300
- // 3. When tapping on an input, the page always scrolls so that the input is centered in the visual viewport.
301
- // This may cause even fixed position elements to scroll off the screen.
302
- // 4. When using the next/previous buttons in the keyboard to navigate between inputs, the whole page always
303
- // scrolls, even if the input is inside a nested scrollable element that could be scrolled instead.
304
- //
305
- // In order to work around these cases, and prevent scrolling without jankiness, we do a few things:
306
- //
307
- // 1. Prevent default on `touchmove` events that are not in a scrollable element. This prevents touch scrolling
308
- // on the window.
309
- // 2. Prevent default on `touchmove` events inside a scrollable element when the scroll position is at the
310
- // top or bottom. This avoids the whole page scrolling instead, but does prevent overscrolling.
311
- // 3. Prevent default on `touchend` events on input elements and handle focusing the element ourselves.
312
- // 4. When focusing an input, apply a transform to trick Safari into thinking the input is at the top
313
- // of the page, which prevents it from scrolling the page. After the input is focused, scroll the element
314
- // into view ourselves, without scrolling the whole page.
315
- // 5. Offset the body by the scroll position using a negative margin and scroll to the top. This should appear the
316
- // same visually, but makes the actual scroll position always zero. This is required to make all of the
317
- // above work or Safari will still try to scroll the page when focusing an input.
318
- // 6. As a last resort, handle window scroll events, and scroll back to the top. This can happen when attempting
319
- // to navigate to an input with the next/previous buttons that's outside a modal.
320
- function preventScrollMobileSafari() {
321
- let scrollable;
322
- let lastY = 0;
323
- let onTouchStart = (e)=>{
324
- // Store the nearest scrollable parent element from the element that the user touched.
325
- scrollable = getScrollParent(e.target);
326
- if (scrollable === document.documentElement && scrollable === document.body) {
327
- return;
328
- }
329
- lastY = e.changedTouches[0].pageY;
330
- };
331
- let onTouchMove = (e)=>{
332
- // Prevent scrolling the window.
333
- if (!scrollable || scrollable === document.documentElement || scrollable === document.body) {
334
- e.preventDefault();
335
- return;
336
- }
337
- // Prevent scrolling up when at the top and scrolling down when at the bottom
338
- // of a nested scrollable area, otherwise mobile Safari will start scrolling
339
- // the window instead. Unfortunately, this disables bounce scrolling when at
340
- // the top but it's the best we can do.
341
- let y = e.changedTouches[0].pageY;
342
- let scrollTop = scrollable.scrollTop;
343
- let bottom = scrollable.scrollHeight - scrollable.clientHeight;
344
- if (bottom === 0) {
345
- return;
346
- }
347
- if (scrollTop <= 0 && y > lastY || scrollTop >= bottom && y < lastY) {
348
- e.preventDefault();
349
- }
350
- lastY = y;
351
- };
352
- let onTouchEnd = (e)=>{
353
- let target = e.target;
354
- // Apply this change if we're not already focused on the target element
355
- if (isInput(target) && target !== document.activeElement) {
356
- e.preventDefault();
357
- // Apply a transform to trick Safari into thinking the input is at the top of the page
358
- // so it doesn't try to scroll it into view. When tapping on an input, this needs to
359
- // be done before the "focus" event, so we have to focus the element ourselves.
360
- target.style.transform = "translateY(-2000px)";
361
- target.focus();
362
- requestAnimationFrame(()=>{
363
- target.style.transform = "";
364
- });
365
- }
366
- };
367
- let onFocus = (e)=>{
368
- let target = e.target;
369
- if (isInput(target)) {
370
- // Transform also needs to be applied in the focus event in cases where focus moves
371
- // other than tapping on an input directly, e.g. the next/previous buttons in the
372
- // software keyboard. In these cases, it seems applying the transform in the focus event
373
- // is good enough, whereas when tapping an input, it must be done before the focus event. 🤷‍♂️
374
- target.style.transform = "translateY(-2000px)";
375
- requestAnimationFrame(()=>{
376
- target.style.transform = "";
377
- // This will have prevented the browser from scrolling the focused element into view,
378
- // so we need to do this ourselves in a way that doesn't cause the whole page to scroll.
379
- if (visualViewport) {
380
- if (visualViewport.height < window.innerHeight) {
381
- // If the keyboard is already visible, do this after one additional frame
382
- // to wait for the transform to be removed.
383
- requestAnimationFrame(()=>{
384
- scrollIntoView(target);
385
- });
386
- } else {
387
- // Otherwise, wait for the visual viewport to resize before scrolling so we can
388
- // measure the correct position to scroll to.
389
- visualViewport.addEventListener("resize", ()=>scrollIntoView(target), {
390
- once: true
391
- });
392
- }
393
- }
394
- });
395
- }
396
- };
397
- let onWindowScroll = ()=>{
398
- // Last resort. If the window scrolled, scroll it back to the top.
399
- // It should always be at the top because the body will have a negative margin (see below).
400
- window.scrollTo(0, 0);
401
- };
402
- // Record the original scroll position so we can restore it.
403
- // Then apply a negative margin to the body to offset it by the scroll position. This will
404
- // enable us to scroll the window to the top, which is required for the rest of this to work.
405
- let scrollX = window.pageXOffset;
406
- let scrollY = window.pageYOffset;
407
- let restoreStyles = chain(setStyle(document.documentElement, "paddingRight", `${window.innerWidth - document.documentElement.clientWidth}px`));
408
- // Scroll to the top. The negative margin on the body will make this appear the same.
409
- window.scrollTo(0, 0);
410
- let removeEvents = chain(addEvent(document, "touchstart", onTouchStart, {
411
- passive: false,
412
- capture: true
413
- }), addEvent(document, "touchmove", onTouchMove, {
414
- passive: false,
415
- capture: true
416
- }), addEvent(document, "touchend", onTouchEnd, {
417
- passive: false,
418
- capture: true
419
- }), addEvent(document, "focus", onFocus, true), addEvent(window, "scroll", onWindowScroll));
420
- return ()=>{
421
- // Restore styles and scroll the page back to where it was.
422
- restoreStyles();
423
- removeEvents();
424
- window.scrollTo(scrollX, scrollY);
425
- };
426
- }
427
- // Sets a CSS property on an element, and returns a function to revert it to the previous value.
428
- function setStyle(element, style, value) {
429
- // https://github.com/microsoft/TypeScript/issues/17827#issuecomment-391663310
430
- // @ts-ignore
431
- let cur = element.style[style];
432
- // @ts-ignore
433
- element.style[style] = value;
434
- return ()=>{
435
- // @ts-ignore
436
- element.style[style] = cur;
437
- };
438
- }
439
- // Adds an event listener to an element, and returns a function to remove it.
440
- function addEvent(target, event, handler, options) {
441
- // @ts-ignore
442
- target.addEventListener(event, handler, options);
443
- return ()=>{
444
- // @ts-ignore
445
- target.removeEventListener(event, handler, options);
446
- };
447
- }
448
- function scrollIntoView(target) {
449
- let root = document.scrollingElement || document.documentElement;
450
- while(target && target !== root){
451
- // Find the parent scrollable element and adjust the scroll position if the target is not already in view.
452
- let scrollable = getScrollParent(target);
453
- if (scrollable !== document.documentElement && scrollable !== document.body && scrollable !== target) {
454
- let scrollableTop = scrollable.getBoundingClientRect().top;
455
- let targetTop = target.getBoundingClientRect().top;
456
- let targetBottom = target.getBoundingClientRect().bottom;
457
- // Buffer is needed for some edge cases
458
- const keyboardHeight = scrollable.getBoundingClientRect().bottom + KEYBOARD_BUFFER;
459
- if (targetBottom > keyboardHeight) {
460
- scrollable.scrollTop += targetTop - scrollableTop;
461
- }
462
- }
463
- // @ts-ignore
464
- target = scrollable.parentElement;
465
- }
466
- }
467
- function isInput(target) {
468
- return target instanceof HTMLInputElement && !nonTextInputTypes.has(target.type) || target instanceof HTMLTextAreaElement || target instanceof HTMLElement && target.isContentEditable;
469
- }
470
-
471
241
  function useSnapPoints({ activeSnapPointProp, setActiveSnapPointProp, snapPoints, drawerRef, overlayRef, fadeFromIndex, onSnapPointChange, direction = "bottom", container, snapToSequentialPoint }) {
472
242
  const [activeSnapPoint, setActiveSnapPoint] = useControllableState({
473
243
  prop: activeSnapPointProp,
474
- defaultProp: snapPoints?.[0],
244
+ defaultProp: snapPoints?.[0] ?? null,
475
245
  onChange: setActiveSnapPointProp
476
246
  });
477
247
  const [windowDimensions, setWindowDimensions] = React.useState(typeof window !== "undefined" ? {
@@ -509,6 +279,11 @@ function useSnapPoints({ activeSnapPointProp, setActiveSnapPointProp, snapPoints
509
279
  height: 0
510
280
  };
511
281
  return snapPoints?.map((snapPoint)=>{
282
+ // FIXME
283
+ // 1 -> container 100% << expected
284
+ // 0.5 -> container 50% << expected
285
+ // 300px -> 300 -> 300px << expected
286
+ // 15rem -> 15 -> 15px << this makes no sense, should fix or disallow
512
287
  const isPx = typeof snapPoint === "string";
513
288
  let snapPointAsNumber = 0;
514
289
  if (isPx) {
@@ -530,7 +305,8 @@ function useSnapPoints({ activeSnapPointProp, setActiveSnapPointProp, snapPoints
530
305
  }, [
531
306
  snapPoints,
532
307
  windowDimensions,
533
- container
308
+ container,
309
+ direction
534
310
  ]);
535
311
  const activeSnapPointOffset = React.useMemo(()=>activeSnapPointIndex !== null ? snapPointsOffset?.[activeSnapPointIndex] : null, [
536
312
  snapPointsOffset,
@@ -681,7 +457,7 @@ function useSnapPoints({ activeSnapPointProp, setActiveSnapPointProp, snapPoints
681
457
  }
682
458
 
683
459
  function useDrawer(props) {
684
- const { open: openProp, onOpenChange, onDrag: onDragProp, onRelease: onReleaseProp, snapPoints, closeThreshold = CLOSE_THRESHOLD, scrollLockTimeout = SCROLL_LOCK_TIMEOUT, dismissible = true, handleOnly = false, fadeFromIndex = snapPoints && snapPoints.length - 1, activeSnapPoint: activeSnapPointProp, setActiveSnapPoint: setActiveSnapPointProp, fixed, modal = true, onClose, nested, noBodyStyles = true, direction = "bottom", defaultOpen = false, disablePreventScroll = true, snapToSequentialPoint = false, preventScrollRestoration = false, repositionInputs = true, onAnimationEnd, container, autoFocus = false, closeOnInteractOutside = true, closeOnEscape = true } = props;
460
+ const { open: openProp, onOpenChange, onDrag: onDragProp, onRelease: onReleaseProp, snapPoints, closeThreshold = CLOSE_THRESHOLD, scrollLockTimeout = SCROLL_LOCK_TIMEOUT, dismissible = true, handleOnly = false, fadeFromIndex = snapPoints && snapPoints.length - 1, activeSnapPoint: activeSnapPointProp, setActiveSnapPoint: setActiveSnapPointProp, fixed, modal = true, onClose, nested, noBodyStyles = true, direction = "bottom", defaultOpen = false, snapToSequentialPoint = false, preventScrollRestoration = false, repositionInputs = true, onAnimationEnd, container, autoFocus = false, closeOnInteractOutside = true, closeOnEscape = true } = props;
685
461
  const [isOpen = false, setIsOpen] = useControllableState({
686
462
  defaultProp: defaultOpen,
687
463
  prop: openProp,
@@ -707,7 +483,6 @@ function useDrawer(props) {
707
483
  });
708
484
  const [hasBeenOpened, setHasBeenOpened] = useState(false);
709
485
  const [isDragging, setIsDragging] = useState(false);
710
- const [justReleased, setJustReleased] = useState(false);
711
486
  const [shouldOverlayAnimate, setShouldOverlayAnimate] = useState(false);
712
487
  const overlayRef = useRef(null);
713
488
  const openTime = useRef(null);
@@ -741,9 +516,6 @@ function useDrawer(props) {
741
516
  direction,
742
517
  snapToSequentialPoint
743
518
  });
744
- usePreventScroll({
745
- isDisabled: !isOpen || isDragging || !modal || justReleased || !hasBeenOpened || !repositionInputs || !disablePreventScroll
746
- });
747
519
  const { restorePositionSetting } = usePositionFixed({
748
520
  isOpen,
749
521
  modal,
@@ -929,12 +701,6 @@ function useDrawer(props) {
929
701
  const timeTaken = dragEndTime.current.getTime() - dragStartTime.current.getTime();
930
702
  const distMoved = pointerStart.current - (isVertical(direction) ? event.pageY : event.pageX);
931
703
  const velocity = Math.abs(distMoved) / timeTaken;
932
- if (velocity > 0.05) {
933
- setJustReleased(true);
934
- setTimeout(()=>{
935
- setJustReleased(false);
936
- }, 200);
937
- }
938
704
  if (snapPoints) {
939
705
  const directionMultiplier = direction === "bottom" || direction === "right" ? 1 : -1;
940
706
  onReleaseSnapPoints({
@@ -1348,7 +1114,7 @@ const LONG_HANDLE_PRESS_TIMEOUT = 250;
1348
1114
  const DOUBLE_TAP_TIMEOUT = 120;
1349
1115
  const DrawerHandle = /*#__PURE__*/ forwardRef((props, ref)=>{
1350
1116
  const { preventCycle = false, children, ...rest } = props;
1351
- const { closeDrawer, isDragging, snapPoints, activeSnapPoint, setActiveSnapPoint, dismissible, handleOnly, isOpen, onPress, onDrag } = useDrawerContext();
1117
+ const { closeDrawer, isDragging, snapPoints, activeSnapPoint, setActiveSnapPoint, dismissible, handleOnly, isOpen, onPress, onDrag, onRelease } = useDrawerContext();
1352
1118
  const closeTimeoutIdRef = useRef(null);
1353
1119
  const shouldCancelInteractionRef = useRef(false);
1354
1120
  function handleStartCycle() {
@@ -1408,7 +1174,10 @@ const DrawerHandle = /*#__PURE__*/ forwardRef((props, ref)=>{
1408
1174
  onPointerMove: (e)=>{
1409
1175
  if (handleOnly) onDrag(e);
1410
1176
  },
1411
- // onPointerUp is already handled by the content component
1177
+ onPointerUp: (e)=>{
1178
+ if (handleOnly) onRelease(e);
1179
+ handleCancelInteraction();
1180
+ },
1412
1181
  "data-drawer-visible": isOpen ? "true" : "false",
1413
1182
  "data-handle": "",
1414
1183
  "aria-hidden": "true",
@@ -72,6 +72,21 @@ const WINDOW_TOP_OFFSET = 26;
72
72
  const DRAG_CLASS = "seed-dragging";
73
73
 
74
74
  const cache = new WeakMap();
75
+ // HTML input types that do not cause the software keyboard to appear.
76
+ const nonTextInputTypes = new Set([
77
+ "checkbox",
78
+ "radio",
79
+ "range",
80
+ "color",
81
+ "file",
82
+ "image",
83
+ "button",
84
+ "submit",
85
+ "reset"
86
+ ]);
87
+ function isInput(target) {
88
+ return target instanceof HTMLInputElement && !nonTextInputTypes.has(target.type) || target instanceof HTMLTextAreaElement || target instanceof HTMLElement && target.isContentEditable;
89
+ }
75
90
  function set(el, styles, ignoreCache = false) {
76
91
  if (!el || !(el instanceof HTMLElement)) return;
77
92
  let originalStyles = {};
@@ -246,255 +261,10 @@ let previousBodyPosition = null;
246
261
  };
247
262
  }
248
263
 
249
- // This code comes from https://github.com/adobe/react-spectrum/blob/main/packages/%40react-aria/overlays/src/usePreventScroll.ts
250
- const KEYBOARD_BUFFER = 24;
251
- const useIsomorphicLayoutEffect = typeof window !== "undefined" ? React.useLayoutEffect : React.useEffect;
252
- function chain(...callbacks) {
253
- return (...args)=>{
254
- for (let callback of callbacks){
255
- if (typeof callback === "function") {
256
- callback(...args);
257
- }
258
- }
259
- };
260
- }
261
- // @ts-ignore
262
- const visualViewport = typeof document !== "undefined" && window.visualViewport;
263
- function isScrollable(node) {
264
- let style = window.getComputedStyle(node);
265
- return /(auto|scroll)/.test(style.overflow + style.overflowX + style.overflowY);
266
- }
267
- function getScrollParent(node) {
268
- if (isScrollable(node)) {
269
- node = node.parentElement;
270
- }
271
- while(node && !isScrollable(node)){
272
- node = node.parentElement;
273
- }
274
- return node || document.scrollingElement || document.documentElement;
275
- }
276
- // HTML input types that do not cause the software keyboard to appear.
277
- const nonTextInputTypes = new Set([
278
- "checkbox",
279
- "radio",
280
- "range",
281
- "color",
282
- "file",
283
- "image",
284
- "button",
285
- "submit",
286
- "reset"
287
- ]);
288
- // The number of active usePreventScroll calls. Used to determine whether to revert back to the original page style/scroll position
289
- let preventScrollCount = 0;
290
- let restore;
291
- /**
292
- * Prevents scrolling on the document body on mount, and
293
- * restores it on unmount. Also ensures that content does not
294
- * shift due to the scrollbars disappearing.
295
- */ function usePreventScroll(options = {}) {
296
- let { isDisabled } = options;
297
- useIsomorphicLayoutEffect(()=>{
298
- if (isDisabled) {
299
- return;
300
- }
301
- preventScrollCount++;
302
- if (preventScrollCount === 1) {
303
- if (isIOS()) {
304
- restore = preventScrollMobileSafari();
305
- }
306
- }
307
- return ()=>{
308
- preventScrollCount--;
309
- if (preventScrollCount === 0) {
310
- restore?.();
311
- }
312
- };
313
- }, [
314
- isDisabled
315
- ]);
316
- }
317
- // Mobile Safari is a whole different beast. Even with overflow: hidden,
318
- // it still scrolls the page in many situations:
319
- //
320
- // 1. When the bottom toolbar and address bar are collapsed, page scrolling is always allowed.
321
- // 2. When the keyboard is visible, the viewport does not resize. Instead, the keyboard covers part of
322
- // it, so it becomes scrollable.
323
- // 3. When tapping on an input, the page always scrolls so that the input is centered in the visual viewport.
324
- // This may cause even fixed position elements to scroll off the screen.
325
- // 4. When using the next/previous buttons in the keyboard to navigate between inputs, the whole page always
326
- // scrolls, even if the input is inside a nested scrollable element that could be scrolled instead.
327
- //
328
- // In order to work around these cases, and prevent scrolling without jankiness, we do a few things:
329
- //
330
- // 1. Prevent default on `touchmove` events that are not in a scrollable element. This prevents touch scrolling
331
- // on the window.
332
- // 2. Prevent default on `touchmove` events inside a scrollable element when the scroll position is at the
333
- // top or bottom. This avoids the whole page scrolling instead, but does prevent overscrolling.
334
- // 3. Prevent default on `touchend` events on input elements and handle focusing the element ourselves.
335
- // 4. When focusing an input, apply a transform to trick Safari into thinking the input is at the top
336
- // of the page, which prevents it from scrolling the page. After the input is focused, scroll the element
337
- // into view ourselves, without scrolling the whole page.
338
- // 5. Offset the body by the scroll position using a negative margin and scroll to the top. This should appear the
339
- // same visually, but makes the actual scroll position always zero. This is required to make all of the
340
- // above work or Safari will still try to scroll the page when focusing an input.
341
- // 6. As a last resort, handle window scroll events, and scroll back to the top. This can happen when attempting
342
- // to navigate to an input with the next/previous buttons that's outside a modal.
343
- function preventScrollMobileSafari() {
344
- let scrollable;
345
- let lastY = 0;
346
- let onTouchStart = (e)=>{
347
- // Store the nearest scrollable parent element from the element that the user touched.
348
- scrollable = getScrollParent(e.target);
349
- if (scrollable === document.documentElement && scrollable === document.body) {
350
- return;
351
- }
352
- lastY = e.changedTouches[0].pageY;
353
- };
354
- let onTouchMove = (e)=>{
355
- // Prevent scrolling the window.
356
- if (!scrollable || scrollable === document.documentElement || scrollable === document.body) {
357
- e.preventDefault();
358
- return;
359
- }
360
- // Prevent scrolling up when at the top and scrolling down when at the bottom
361
- // of a nested scrollable area, otherwise mobile Safari will start scrolling
362
- // the window instead. Unfortunately, this disables bounce scrolling when at
363
- // the top but it's the best we can do.
364
- let y = e.changedTouches[0].pageY;
365
- let scrollTop = scrollable.scrollTop;
366
- let bottom = scrollable.scrollHeight - scrollable.clientHeight;
367
- if (bottom === 0) {
368
- return;
369
- }
370
- if (scrollTop <= 0 && y > lastY || scrollTop >= bottom && y < lastY) {
371
- e.preventDefault();
372
- }
373
- lastY = y;
374
- };
375
- let onTouchEnd = (e)=>{
376
- let target = e.target;
377
- // Apply this change if we're not already focused on the target element
378
- if (isInput(target) && target !== document.activeElement) {
379
- e.preventDefault();
380
- // Apply a transform to trick Safari into thinking the input is at the top of the page
381
- // so it doesn't try to scroll it into view. When tapping on an input, this needs to
382
- // be done before the "focus" event, so we have to focus the element ourselves.
383
- target.style.transform = "translateY(-2000px)";
384
- target.focus();
385
- requestAnimationFrame(()=>{
386
- target.style.transform = "";
387
- });
388
- }
389
- };
390
- let onFocus = (e)=>{
391
- let target = e.target;
392
- if (isInput(target)) {
393
- // Transform also needs to be applied in the focus event in cases where focus moves
394
- // other than tapping on an input directly, e.g. the next/previous buttons in the
395
- // software keyboard. In these cases, it seems applying the transform in the focus event
396
- // is good enough, whereas when tapping an input, it must be done before the focus event. 🤷‍♂️
397
- target.style.transform = "translateY(-2000px)";
398
- requestAnimationFrame(()=>{
399
- target.style.transform = "";
400
- // This will have prevented the browser from scrolling the focused element into view,
401
- // so we need to do this ourselves in a way that doesn't cause the whole page to scroll.
402
- if (visualViewport) {
403
- if (visualViewport.height < window.innerHeight) {
404
- // If the keyboard is already visible, do this after one additional frame
405
- // to wait for the transform to be removed.
406
- requestAnimationFrame(()=>{
407
- scrollIntoView(target);
408
- });
409
- } else {
410
- // Otherwise, wait for the visual viewport to resize before scrolling so we can
411
- // measure the correct position to scroll to.
412
- visualViewport.addEventListener("resize", ()=>scrollIntoView(target), {
413
- once: true
414
- });
415
- }
416
- }
417
- });
418
- }
419
- };
420
- let onWindowScroll = ()=>{
421
- // Last resort. If the window scrolled, scroll it back to the top.
422
- // It should always be at the top because the body will have a negative margin (see below).
423
- window.scrollTo(0, 0);
424
- };
425
- // Record the original scroll position so we can restore it.
426
- // Then apply a negative margin to the body to offset it by the scroll position. This will
427
- // enable us to scroll the window to the top, which is required for the rest of this to work.
428
- let scrollX = window.pageXOffset;
429
- let scrollY = window.pageYOffset;
430
- let restoreStyles = chain(setStyle(document.documentElement, "paddingRight", `${window.innerWidth - document.documentElement.clientWidth}px`));
431
- // Scroll to the top. The negative margin on the body will make this appear the same.
432
- window.scrollTo(0, 0);
433
- let removeEvents = chain(addEvent(document, "touchstart", onTouchStart, {
434
- passive: false,
435
- capture: true
436
- }), addEvent(document, "touchmove", onTouchMove, {
437
- passive: false,
438
- capture: true
439
- }), addEvent(document, "touchend", onTouchEnd, {
440
- passive: false,
441
- capture: true
442
- }), addEvent(document, "focus", onFocus, true), addEvent(window, "scroll", onWindowScroll));
443
- return ()=>{
444
- // Restore styles and scroll the page back to where it was.
445
- restoreStyles();
446
- removeEvents();
447
- window.scrollTo(scrollX, scrollY);
448
- };
449
- }
450
- // Sets a CSS property on an element, and returns a function to revert it to the previous value.
451
- function setStyle(element, style, value) {
452
- // https://github.com/microsoft/TypeScript/issues/17827#issuecomment-391663310
453
- // @ts-ignore
454
- let cur = element.style[style];
455
- // @ts-ignore
456
- element.style[style] = value;
457
- return ()=>{
458
- // @ts-ignore
459
- element.style[style] = cur;
460
- };
461
- }
462
- // Adds an event listener to an element, and returns a function to remove it.
463
- function addEvent(target, event, handler, options) {
464
- // @ts-ignore
465
- target.addEventListener(event, handler, options);
466
- return ()=>{
467
- // @ts-ignore
468
- target.removeEventListener(event, handler, options);
469
- };
470
- }
471
- function scrollIntoView(target) {
472
- let root = document.scrollingElement || document.documentElement;
473
- while(target && target !== root){
474
- // Find the parent scrollable element and adjust the scroll position if the target is not already in view.
475
- let scrollable = getScrollParent(target);
476
- if (scrollable !== document.documentElement && scrollable !== document.body && scrollable !== target) {
477
- let scrollableTop = scrollable.getBoundingClientRect().top;
478
- let targetTop = target.getBoundingClientRect().top;
479
- let targetBottom = target.getBoundingClientRect().bottom;
480
- // Buffer is needed for some edge cases
481
- const keyboardHeight = scrollable.getBoundingClientRect().bottom + KEYBOARD_BUFFER;
482
- if (targetBottom > keyboardHeight) {
483
- scrollable.scrollTop += targetTop - scrollableTop;
484
- }
485
- }
486
- // @ts-ignore
487
- target = scrollable.parentElement;
488
- }
489
- }
490
- function isInput(target) {
491
- return target instanceof HTMLInputElement && !nonTextInputTypes.has(target.type) || target instanceof HTMLTextAreaElement || target instanceof HTMLElement && target.isContentEditable;
492
- }
493
-
494
264
  function useSnapPoints({ activeSnapPointProp, setActiveSnapPointProp, snapPoints, drawerRef, overlayRef, fadeFromIndex, onSnapPointChange, direction = "bottom", container, snapToSequentialPoint }) {
495
265
  const [activeSnapPoint, setActiveSnapPoint] = reactUseControllableState.useControllableState({
496
266
  prop: activeSnapPointProp,
497
- defaultProp: snapPoints?.[0],
267
+ defaultProp: snapPoints?.[0] ?? null,
498
268
  onChange: setActiveSnapPointProp
499
269
  });
500
270
  const [windowDimensions, setWindowDimensions] = React__default.default.useState(typeof window !== "undefined" ? {
@@ -532,6 +302,11 @@ function useSnapPoints({ activeSnapPointProp, setActiveSnapPointProp, snapPoints
532
302
  height: 0
533
303
  };
534
304
  return snapPoints?.map((snapPoint)=>{
305
+ // FIXME
306
+ // 1 -> container 100% << expected
307
+ // 0.5 -> container 50% << expected
308
+ // 300px -> 300 -> 300px << expected
309
+ // 15rem -> 15 -> 15px << this makes no sense, should fix or disallow
535
310
  const isPx = typeof snapPoint === "string";
536
311
  let snapPointAsNumber = 0;
537
312
  if (isPx) {
@@ -553,7 +328,8 @@ function useSnapPoints({ activeSnapPointProp, setActiveSnapPointProp, snapPoints
553
328
  }, [
554
329
  snapPoints,
555
330
  windowDimensions,
556
- container
331
+ container,
332
+ direction
557
333
  ]);
558
334
  const activeSnapPointOffset = React__default.default.useMemo(()=>activeSnapPointIndex !== null ? snapPointsOffset?.[activeSnapPointIndex] : null, [
559
335
  snapPointsOffset,
@@ -704,7 +480,7 @@ function useSnapPoints({ activeSnapPointProp, setActiveSnapPointProp, snapPoints
704
480
  }
705
481
 
706
482
  function useDrawer(props) {
707
- const { open: openProp, onOpenChange, onDrag: onDragProp, onRelease: onReleaseProp, snapPoints, closeThreshold = CLOSE_THRESHOLD, scrollLockTimeout = SCROLL_LOCK_TIMEOUT, dismissible = true, handleOnly = false, fadeFromIndex = snapPoints && snapPoints.length - 1, activeSnapPoint: activeSnapPointProp, setActiveSnapPoint: setActiveSnapPointProp, fixed, modal = true, onClose, nested, noBodyStyles = true, direction = "bottom", defaultOpen = false, disablePreventScroll = true, snapToSequentialPoint = false, preventScrollRestoration = false, repositionInputs = true, onAnimationEnd, container, autoFocus = false, closeOnInteractOutside = true, closeOnEscape = true } = props;
483
+ const { open: openProp, onOpenChange, onDrag: onDragProp, onRelease: onReleaseProp, snapPoints, closeThreshold = CLOSE_THRESHOLD, scrollLockTimeout = SCROLL_LOCK_TIMEOUT, dismissible = true, handleOnly = false, fadeFromIndex = snapPoints && snapPoints.length - 1, activeSnapPoint: activeSnapPointProp, setActiveSnapPoint: setActiveSnapPointProp, fixed, modal = true, onClose, nested, noBodyStyles = true, direction = "bottom", defaultOpen = false, snapToSequentialPoint = false, preventScrollRestoration = false, repositionInputs = true, onAnimationEnd, container, autoFocus = false, closeOnInteractOutside = true, closeOnEscape = true } = props;
708
484
  const [isOpen = false, setIsOpen] = reactUseControllableState.useControllableState({
709
485
  defaultProp: defaultOpen,
710
486
  prop: openProp,
@@ -730,7 +506,6 @@ function useDrawer(props) {
730
506
  });
731
507
  const [hasBeenOpened, setHasBeenOpened] = React.useState(false);
732
508
  const [isDragging, setIsDragging] = React.useState(false);
733
- const [justReleased, setJustReleased] = React.useState(false);
734
509
  const [shouldOverlayAnimate, setShouldOverlayAnimate] = React.useState(false);
735
510
  const overlayRef = React.useRef(null);
736
511
  const openTime = React.useRef(null);
@@ -764,9 +539,6 @@ function useDrawer(props) {
764
539
  direction,
765
540
  snapToSequentialPoint
766
541
  });
767
- usePreventScroll({
768
- isDisabled: !isOpen || isDragging || !modal || justReleased || !hasBeenOpened || !repositionInputs || !disablePreventScroll
769
- });
770
542
  const { restorePositionSetting } = usePositionFixed({
771
543
  isOpen,
772
544
  modal,
@@ -952,12 +724,6 @@ function useDrawer(props) {
952
724
  const timeTaken = dragEndTime.current.getTime() - dragStartTime.current.getTime();
953
725
  const distMoved = pointerStart.current - (isVertical(direction) ? event.pageY : event.pageX);
954
726
  const velocity = Math.abs(distMoved) / timeTaken;
955
- if (velocity > 0.05) {
956
- setJustReleased(true);
957
- setTimeout(()=>{
958
- setJustReleased(false);
959
- }, 200);
960
- }
961
727
  if (snapPoints) {
962
728
  const directionMultiplier = direction === "bottom" || direction === "right" ? 1 : -1;
963
729
  onReleaseSnapPoints({
@@ -1371,7 +1137,7 @@ const LONG_HANDLE_PRESS_TIMEOUT = 250;
1371
1137
  const DOUBLE_TAP_TIMEOUT = 120;
1372
1138
  const DrawerHandle = /*#__PURE__*/ React.forwardRef((props, ref)=>{
1373
1139
  const { preventCycle = false, children, ...rest } = props;
1374
- const { closeDrawer, isDragging, snapPoints, activeSnapPoint, setActiveSnapPoint, dismissible, handleOnly, isOpen, onPress, onDrag } = useDrawerContext();
1140
+ const { closeDrawer, isDragging, snapPoints, activeSnapPoint, setActiveSnapPoint, dismissible, handleOnly, isOpen, onPress, onDrag, onRelease } = useDrawerContext();
1375
1141
  const closeTimeoutIdRef = React.useRef(null);
1376
1142
  const shouldCancelInteractionRef = React.useRef(false);
1377
1143
  function handleStartCycle() {
@@ -1431,7 +1197,10 @@ const DrawerHandle = /*#__PURE__*/ React.forwardRef((props, ref)=>{
1431
1197
  onPointerMove: (e)=>{
1432
1198
  if (handleOnly) onDrag(e);
1433
1199
  },
1434
- // onPointerUp is already handled by the content component
1200
+ onPointerUp: (e)=>{
1201
+ if (handleOnly) onRelease(e);
1202
+ handleCancelInteraction();
1203
+ },
1435
1204
  "data-drawer-visible": isOpen ? "true" : "false",
1436
1205
  "data-handle": "",
1437
1206
  "aria-hidden": "true",
package/lib/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- var Drawer12s = require('./Drawer-12s-a4zbhVrK.cjs');
1
+ var Drawer12s = require('./Drawer-12s-Yr_NcCoF.cjs');
2
2
 
3
3
  var Drawer_namespace = {
4
4
  __proto__: null,
package/lib/index.d.ts CHANGED
@@ -36,7 +36,7 @@ interface UseDrawerProps {
36
36
  handleOnly?: boolean;
37
37
  /**
38
38
  * When `false` dragging, clicking outside, pressing esc, etc. will not close the drawer.
39
- * Use this in comination with the `open` prop, otherwise you won't be able to open/close the drawer.
39
+ * Use this in combination with the `open` prop, otherwise you won't be able to open/close the drawer.
40
40
  * @default true
41
41
  */
42
42
  dismissible?: boolean;
@@ -59,11 +59,6 @@ interface UseDrawerProps {
59
59
  * @default false
60
60
  */
61
61
  defaultOpen?: boolean;
62
- /**
63
- * When set to `true` prevents scrolling on the document body on mount, and restores it on unmount.
64
- * @default false
65
- */
66
- disablePreventScroll?: boolean;
67
62
  /**
68
63
  * When `true` Vaul will reposition inputs rather than scroll then into view if the keyboard is in the way.
69
64
  * Setting it to `false` will fall back to the default browser behavior.
@@ -87,7 +82,7 @@ interface UseDrawerProps {
87
82
  autoFocus?: boolean;
88
83
  /**
89
84
  * Array of snap points to use.
90
- * Example: snapPoints={[0, 100, 200]} will use the first snap point at 0px, the second at 100px, and the third at 200px.
85
+ * Example: snapPoints={["100px", "200px", 1]} will use the snap points 100px, 200px and fully open (1 = 100% of the container).
91
86
  * @default undefined
92
87
  */
93
88
  snapPoints?: (number | string)[];
package/lib/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { D as DrawerBackdrop, a as DrawerCloseButton, b as DrawerContent, c as DrawerDescription, d as DrawerHandle, e as DrawerPositioner, f as DrawerRoot, g as DrawerTitle, h as DrawerTrigger } from './Drawer-12s-COJG4T4l.js';
2
- export { u as useDrawer, i as useDrawerContext } from './Drawer-12s-COJG4T4l.js';
1
+ import { D as DrawerBackdrop, a as DrawerCloseButton, b as DrawerContent, c as DrawerDescription, d as DrawerHandle, e as DrawerPositioner, f as DrawerRoot, g as DrawerTitle, h as DrawerTrigger } from './Drawer-12s-BOMSoUDc.js';
2
+ export { u as useDrawer, i as useDrawerContext } from './Drawer-12s-BOMSoUDc.js';
3
3
 
4
4
  var Drawer_namespace = {
5
5
  __proto__: null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seed-design/react-drawer",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/daangn/seed-design.git",
package/src/Drawer.tsx CHANGED
@@ -325,6 +325,7 @@ export const DrawerHandle = forwardRef<HTMLDivElement, DrawerHandleProps>((props
325
325
  isOpen,
326
326
  onPress,
327
327
  onDrag,
328
+ onRelease,
328
329
  } = useDrawerContext();
329
330
 
330
331
  const closeTimeoutIdRef = useRef<number | null>(null);
@@ -396,7 +397,10 @@ export const DrawerHandle = forwardRef<HTMLDivElement, DrawerHandleProps>((props
396
397
  onPointerMove={(e) => {
397
398
  if (handleOnly) onDrag(e);
398
399
  }}
399
- // onPointerUp is already handled by the content component
400
+ onPointerUp={(e) => {
401
+ if (handleOnly) onRelease(e);
402
+ handleCancelInteraction();
403
+ }}
400
404
  data-drawer-visible={isOpen ? "true" : "false"}
401
405
  data-handle=""
402
406
  aria-hidden="true"
package/src/helpers.ts CHANGED
@@ -6,6 +6,27 @@ interface Style {
6
6
 
7
7
  const cache = new WeakMap();
8
8
 
9
+ // HTML input types that do not cause the software keyboard to appear.
10
+ const nonTextInputTypes = new Set([
11
+ "checkbox",
12
+ "radio",
13
+ "range",
14
+ "color",
15
+ "file",
16
+ "image",
17
+ "button",
18
+ "submit",
19
+ "reset",
20
+ ]);
21
+
22
+ export function isInput(target: Element) {
23
+ return (
24
+ (target instanceof HTMLInputElement && !nonTextInputTypes.has(target.type)) ||
25
+ target instanceof HTMLTextAreaElement ||
26
+ (target instanceof HTMLElement && target.isContentEditable)
27
+ );
28
+ }
29
+
9
30
  export function isInView(el: HTMLElement): boolean {
10
31
  const rect = el.getBoundingClientRect();
11
32
 
@@ -20,8 +20,8 @@ export function useSnapPoints({
20
20
  setActiveSnapPointProp?(snapPoint: number | null | string): void;
21
21
  snapPoints?: (number | string)[];
22
22
  fadeFromIndex?: number;
23
- drawerRef: React.RefObject<HTMLDivElement>;
24
- overlayRef: React.RefObject<HTMLDivElement>;
23
+ drawerRef: React.RefObject<HTMLDivElement | null>;
24
+ overlayRef: React.RefObject<HTMLDivElement | null>;
25
25
  onSnapPointChange(activeSnapPointIndex: number): void;
26
26
  direction?: DrawerDirection;
27
27
  container?: HTMLElement | null | undefined;
@@ -29,7 +29,7 @@ export function useSnapPoints({
29
29
  }) {
30
30
  const [activeSnapPoint, setActiveSnapPoint] = useControllableState<string | number | null>({
31
31
  prop: activeSnapPointProp,
32
- defaultProp: snapPoints?.[0],
32
+ defaultProp: snapPoints?.[0] ?? null,
33
33
  onChange: setActiveSnapPointProp,
34
34
  });
35
35
 
@@ -84,6 +84,12 @@ export function useSnapPoints({
84
84
 
85
85
  return (
86
86
  snapPoints?.map((snapPoint) => {
87
+ // FIXME
88
+ // 1 -> container 100% << expected
89
+ // 0.5 -> container 50% << expected
90
+ // 300px -> 300 -> 300px << expected
91
+ // 15rem -> 15 -> 15px << this makes no sense, should fix or disallow
92
+
87
93
  const isPx = typeof snapPoint === "string";
88
94
  let snapPointAsNumber = 0;
89
95
 
@@ -119,7 +125,7 @@ export function useSnapPoints({
119
125
  return width;
120
126
  }) ?? []
121
127
  );
122
- }, [snapPoints, windowDimensions, container]);
128
+ }, [snapPoints, windowDimensions, container, direction]);
123
129
 
124
130
  const activeSnapPointOffset = React.useMemo(
125
131
  () => (activeSnapPointIndex !== null ? snapPointsOffset?.[activeSnapPointIndex] : null),
package/src/useDrawer.ts CHANGED
@@ -9,9 +9,8 @@ import {
9
9
  VELOCITY_THRESHOLD,
10
10
  WINDOW_TOP_OFFSET,
11
11
  } from "./constants";
12
- import { dampenValue, getTranslate, isVertical, reset, set } from "./helpers";
12
+ import { dampenValue, getTranslate, isInput, isVertical, reset, set } from "./helpers";
13
13
  import { usePositionFixed } from "./use-position-fixed";
14
- import { isInput, usePreventScroll } from "./use-prevent-scroll";
15
14
  import { useSnapPoints } from "./use-snap-points";
16
15
 
17
16
  export interface UseDrawerProps {
@@ -47,7 +46,7 @@ export interface UseDrawerProps {
47
46
  handleOnly?: boolean;
48
47
  /**
49
48
  * When `false` dragging, clicking outside, pressing esc, etc. will not close the drawer.
50
- * Use this in comination with the `open` prop, otherwise you won't be able to open/close the drawer.
49
+ * Use this in combination with the `open` prop, otherwise you won't be able to open/close the drawer.
51
50
  * @default true
52
51
  */
53
52
  dismissible?: boolean;
@@ -70,11 +69,6 @@ export interface UseDrawerProps {
70
69
  * @default false
71
70
  */
72
71
  defaultOpen?: boolean;
73
- /**
74
- * When set to `true` prevents scrolling on the document body on mount, and restores it on unmount.
75
- * @default false
76
- */
77
- disablePreventScroll?: boolean;
78
72
  /**
79
73
  * When `true` Vaul will reposition inputs rather than scroll then into view if the keyboard is in the way.
80
74
  * Setting it to `false` will fall back to the default browser behavior.
@@ -99,7 +93,7 @@ export interface UseDrawerProps {
99
93
 
100
94
  /**
101
95
  * Array of snap points to use.
102
- * Example: snapPoints={[0, 100, 200]} will use the first snap point at 0px, the second at 100px, and the third at 200px.
96
+ * Example: snapPoints={["100px", "200px", 1]} will use the snap points 100px, 200px and fully open (1 = 100% of the container).
103
97
  * @default undefined
104
98
  */
105
99
  snapPoints?: (number | string)[];
@@ -145,7 +139,6 @@ export function useDrawer(props: UseDrawerProps) {
145
139
  noBodyStyles = true,
146
140
  direction = "bottom",
147
141
  defaultOpen = false,
148
- disablePreventScroll = true,
149
142
  snapToSequentialPoint = false,
150
143
  preventScrollRestoration = false,
151
144
  repositionInputs = true,
@@ -186,7 +179,6 @@ export function useDrawer(props: UseDrawerProps) {
186
179
 
187
180
  const [hasBeenOpened, setHasBeenOpened] = useState<boolean>(false);
188
181
  const [isDragging, setIsDragging] = useState<boolean>(false);
189
- const [justReleased, setJustReleased] = useState<boolean>(false);
190
182
  const [shouldOverlayAnimate, setShouldOverlayAnimate] = useState<boolean>(false);
191
183
 
192
184
  const overlayRef = useRef<HTMLDivElement>(null);
@@ -234,17 +226,6 @@ export function useDrawer(props: UseDrawerProps) {
234
226
  snapToSequentialPoint,
235
227
  });
236
228
 
237
- usePreventScroll({
238
- isDisabled:
239
- !isOpen ||
240
- isDragging ||
241
- !modal ||
242
- justReleased ||
243
- !hasBeenOpened ||
244
- !repositionInputs ||
245
- !disablePreventScroll,
246
- });
247
-
248
229
  const { restorePositionSetting } = usePositionFixed({
249
230
  isOpen,
250
231
  modal,
@@ -502,13 +483,6 @@ export function useDrawer(props: UseDrawerProps) {
502
483
  const distMoved = pointerStart.current - (isVertical(direction) ? event.pageY : event.pageX);
503
484
  const velocity = Math.abs(distMoved) / timeTaken;
504
485
 
505
- if (velocity > 0.05) {
506
- setJustReleased(true);
507
- setTimeout(() => {
508
- setJustReleased(false);
509
- }, 200);
510
- }
511
-
512
486
  if (snapPoints) {
513
487
  const directionMultiplier = direction === "bottom" || direction === "right" ? 1 : -1;
514
488
  onReleaseSnapPoints({
@@ -1,309 +0,0 @@
1
- // This code comes from https://github.com/adobe/react-spectrum/blob/main/packages/%40react-aria/overlays/src/usePreventScroll.ts
2
-
3
- import { useEffect, useLayoutEffect } from "react";
4
- import { isIOS } from "./browser";
5
-
6
- const KEYBOARD_BUFFER = 24;
7
-
8
- export const useIsomorphicLayoutEffect =
9
- typeof window !== "undefined" ? useLayoutEffect : useEffect;
10
-
11
- interface PreventScrollOptions {
12
- /** Whether the scroll lock is disabled. */
13
- isDisabled?: boolean;
14
- focusCallback?: () => void;
15
- }
16
-
17
- function chain(...callbacks: any[]): (...args: any[]) => void {
18
- return (...args: any[]) => {
19
- for (let callback of callbacks) {
20
- if (typeof callback === "function") {
21
- callback(...args);
22
- }
23
- }
24
- };
25
- }
26
-
27
- // @ts-ignore
28
- const visualViewport = typeof document !== "undefined" && window.visualViewport;
29
-
30
- export function isScrollable(node: Element): boolean {
31
- let style = window.getComputedStyle(node);
32
- return /(auto|scroll)/.test(style.overflow + style.overflowX + style.overflowY);
33
- }
34
-
35
- export function getScrollParent(node: Element): Element {
36
- if (isScrollable(node)) {
37
- node = node.parentElement as HTMLElement;
38
- }
39
-
40
- while (node && !isScrollable(node)) {
41
- node = node.parentElement as HTMLElement;
42
- }
43
-
44
- return node || document.scrollingElement || document.documentElement;
45
- }
46
-
47
- // HTML input types that do not cause the software keyboard to appear.
48
- const nonTextInputTypes = new Set([
49
- "checkbox",
50
- "radio",
51
- "range",
52
- "color",
53
- "file",
54
- "image",
55
- "button",
56
- "submit",
57
- "reset",
58
- ]);
59
-
60
- // The number of active usePreventScroll calls. Used to determine whether to revert back to the original page style/scroll position
61
- let preventScrollCount = 0;
62
- let restore: () => void;
63
-
64
- /**
65
- * Prevents scrolling on the document body on mount, and
66
- * restores it on unmount. Also ensures that content does not
67
- * shift due to the scrollbars disappearing.
68
- */
69
- export function usePreventScroll(options: PreventScrollOptions = {}) {
70
- let { isDisabled } = options;
71
-
72
- useIsomorphicLayoutEffect(() => {
73
- if (isDisabled) {
74
- return;
75
- }
76
-
77
- preventScrollCount++;
78
- if (preventScrollCount === 1) {
79
- if (isIOS()) {
80
- restore = preventScrollMobileSafari();
81
- }
82
- }
83
-
84
- return () => {
85
- preventScrollCount--;
86
- if (preventScrollCount === 0) {
87
- restore?.();
88
- }
89
- };
90
- }, [isDisabled]);
91
- }
92
-
93
- // Mobile Safari is a whole different beast. Even with overflow: hidden,
94
- // it still scrolls the page in many situations:
95
- //
96
- // 1. When the bottom toolbar and address bar are collapsed, page scrolling is always allowed.
97
- // 2. When the keyboard is visible, the viewport does not resize. Instead, the keyboard covers part of
98
- // it, so it becomes scrollable.
99
- // 3. When tapping on an input, the page always scrolls so that the input is centered in the visual viewport.
100
- // This may cause even fixed position elements to scroll off the screen.
101
- // 4. When using the next/previous buttons in the keyboard to navigate between inputs, the whole page always
102
- // scrolls, even if the input is inside a nested scrollable element that could be scrolled instead.
103
- //
104
- // In order to work around these cases, and prevent scrolling without jankiness, we do a few things:
105
- //
106
- // 1. Prevent default on `touchmove` events that are not in a scrollable element. This prevents touch scrolling
107
- // on the window.
108
- // 2. Prevent default on `touchmove` events inside a scrollable element when the scroll position is at the
109
- // top or bottom. This avoids the whole page scrolling instead, but does prevent overscrolling.
110
- // 3. Prevent default on `touchend` events on input elements and handle focusing the element ourselves.
111
- // 4. When focusing an input, apply a transform to trick Safari into thinking the input is at the top
112
- // of the page, which prevents it from scrolling the page. After the input is focused, scroll the element
113
- // into view ourselves, without scrolling the whole page.
114
- // 5. Offset the body by the scroll position using a negative margin and scroll to the top. This should appear the
115
- // same visually, but makes the actual scroll position always zero. This is required to make all of the
116
- // above work or Safari will still try to scroll the page when focusing an input.
117
- // 6. As a last resort, handle window scroll events, and scroll back to the top. This can happen when attempting
118
- // to navigate to an input with the next/previous buttons that's outside a modal.
119
- function preventScrollMobileSafari() {
120
- let scrollable: Element;
121
- let lastY = 0;
122
- let onTouchStart = (e: TouchEvent) => {
123
- // Store the nearest scrollable parent element from the element that the user touched.
124
- scrollable = getScrollParent(e.target as Element);
125
- if (scrollable === document.documentElement && scrollable === document.body) {
126
- return;
127
- }
128
-
129
- lastY = e.changedTouches[0].pageY;
130
- };
131
-
132
- let onTouchMove = (e: TouchEvent) => {
133
- // Prevent scrolling the window.
134
- if (!scrollable || scrollable === document.documentElement || scrollable === document.body) {
135
- e.preventDefault();
136
- return;
137
- }
138
-
139
- // Prevent scrolling up when at the top and scrolling down when at the bottom
140
- // of a nested scrollable area, otherwise mobile Safari will start scrolling
141
- // the window instead. Unfortunately, this disables bounce scrolling when at
142
- // the top but it's the best we can do.
143
- let y = e.changedTouches[0].pageY;
144
- let scrollTop = scrollable.scrollTop;
145
- let bottom = scrollable.scrollHeight - scrollable.clientHeight;
146
-
147
- if (bottom === 0) {
148
- return;
149
- }
150
-
151
- if ((scrollTop <= 0 && y > lastY) || (scrollTop >= bottom && y < lastY)) {
152
- e.preventDefault();
153
- }
154
-
155
- lastY = y;
156
- };
157
-
158
- let onTouchEnd = (e: TouchEvent) => {
159
- let target = e.target as HTMLElement;
160
-
161
- // Apply this change if we're not already focused on the target element
162
- if (isInput(target) && target !== document.activeElement) {
163
- e.preventDefault();
164
-
165
- // Apply a transform to trick Safari into thinking the input is at the top of the page
166
- // so it doesn't try to scroll it into view. When tapping on an input, this needs to
167
- // be done before the "focus" event, so we have to focus the element ourselves.
168
- target.style.transform = "translateY(-2000px)";
169
- target.focus();
170
- requestAnimationFrame(() => {
171
- target.style.transform = "";
172
- });
173
- }
174
- };
175
-
176
- let onFocus = (e: FocusEvent) => {
177
- let target = e.target as HTMLElement;
178
- if (isInput(target)) {
179
- // Transform also needs to be applied in the focus event in cases where focus moves
180
- // other than tapping on an input directly, e.g. the next/previous buttons in the
181
- // software keyboard. In these cases, it seems applying the transform in the focus event
182
- // is good enough, whereas when tapping an input, it must be done before the focus event. 🤷‍♂️
183
- target.style.transform = "translateY(-2000px)";
184
- requestAnimationFrame(() => {
185
- target.style.transform = "";
186
-
187
- // This will have prevented the browser from scrolling the focused element into view,
188
- // so we need to do this ourselves in a way that doesn't cause the whole page to scroll.
189
- if (visualViewport) {
190
- if (visualViewport.height < window.innerHeight) {
191
- // If the keyboard is already visible, do this after one additional frame
192
- // to wait for the transform to be removed.
193
- requestAnimationFrame(() => {
194
- scrollIntoView(target);
195
- });
196
- } else {
197
- // Otherwise, wait for the visual viewport to resize before scrolling so we can
198
- // measure the correct position to scroll to.
199
- visualViewport.addEventListener("resize", () => scrollIntoView(target), { once: true });
200
- }
201
- }
202
- });
203
- }
204
- };
205
-
206
- let onWindowScroll = () => {
207
- // Last resort. If the window scrolled, scroll it back to the top.
208
- // It should always be at the top because the body will have a negative margin (see below).
209
- window.scrollTo(0, 0);
210
- };
211
-
212
- // Record the original scroll position so we can restore it.
213
- // Then apply a negative margin to the body to offset it by the scroll position. This will
214
- // enable us to scroll the window to the top, which is required for the rest of this to work.
215
- let scrollX = window.pageXOffset;
216
- let scrollY = window.pageYOffset;
217
-
218
- let restoreStyles = chain(
219
- setStyle(
220
- document.documentElement,
221
- "paddingRight",
222
- `${window.innerWidth - document.documentElement.clientWidth}px`,
223
- ),
224
- // setStyle(document.documentElement, 'overflow', 'hidden'),
225
- // setStyle(document.body, 'marginTop', `-${scrollY}px`),
226
- );
227
-
228
- // Scroll to the top. The negative margin on the body will make this appear the same.
229
- window.scrollTo(0, 0);
230
-
231
- let removeEvents = chain(
232
- addEvent(document, "touchstart", onTouchStart, { passive: false, capture: true }),
233
- addEvent(document, "touchmove", onTouchMove, { passive: false, capture: true }),
234
- addEvent(document, "touchend", onTouchEnd, { passive: false, capture: true }),
235
- addEvent(document, "focus", onFocus, true),
236
- addEvent(window, "scroll", onWindowScroll),
237
- );
238
-
239
- return () => {
240
- // Restore styles and scroll the page back to where it was.
241
- restoreStyles();
242
- removeEvents();
243
- window.scrollTo(scrollX, scrollY);
244
- };
245
- }
246
-
247
- // Sets a CSS property on an element, and returns a function to revert it to the previous value.
248
- function setStyle(element: HTMLElement, style: keyof React.CSSProperties, value: string) {
249
- // https://github.com/microsoft/TypeScript/issues/17827#issuecomment-391663310
250
- // @ts-ignore
251
- let cur = element.style[style];
252
- // @ts-ignore
253
- element.style[style] = value;
254
-
255
- return () => {
256
- // @ts-ignore
257
- element.style[style] = cur;
258
- };
259
- }
260
-
261
- // Adds an event listener to an element, and returns a function to remove it.
262
- function addEvent<K extends keyof GlobalEventHandlersEventMap>(
263
- target: EventTarget,
264
- event: K,
265
- handler: (this: Document, ev: GlobalEventHandlersEventMap[K]) => any,
266
- options?: boolean | AddEventListenerOptions,
267
- ) {
268
- // @ts-ignore
269
- target.addEventListener(event, handler, options);
270
-
271
- return () => {
272
- // @ts-ignore
273
- target.removeEventListener(event, handler, options);
274
- };
275
- }
276
-
277
- function scrollIntoView(target: Element) {
278
- let root = document.scrollingElement || document.documentElement;
279
- while (target && target !== root) {
280
- // Find the parent scrollable element and adjust the scroll position if the target is not already in view.
281
- let scrollable = getScrollParent(target);
282
- if (
283
- scrollable !== document.documentElement &&
284
- scrollable !== document.body &&
285
- scrollable !== target
286
- ) {
287
- let scrollableTop = scrollable.getBoundingClientRect().top;
288
- let targetTop = target.getBoundingClientRect().top;
289
- let targetBottom = target.getBoundingClientRect().bottom;
290
- // Buffer is needed for some edge cases
291
- const keyboardHeight = scrollable.getBoundingClientRect().bottom + KEYBOARD_BUFFER;
292
-
293
- if (targetBottom > keyboardHeight) {
294
- scrollable.scrollTop += targetTop - scrollableTop;
295
- }
296
- }
297
-
298
- // @ts-ignore
299
- target = scrollable.parentElement;
300
- }
301
- }
302
-
303
- export function isInput(target: Element) {
304
- return (
305
- (target instanceof HTMLInputElement && !nonTextInputTypes.has(target.type)) ||
306
- target instanceof HTMLTextAreaElement ||
307
- (target instanceof HTMLElement && target.isContentEditable)
308
- );
309
- }