@seed-design/react-drawer 1.0.1 → 1.0.3

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 = false, 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,
@@ -760,7 +532,9 @@ function useDrawer(props) {
760
532
  setIsDragging(true);
761
533
  dragStartTime.current = new Date();
762
534
  if (isIOS()) {
763
- window.addEventListener("touchend", ()=>isAllowedToDrag.current = false, {
535
+ window.addEventListener("touchend", ()=>{
536
+ isAllowedToDrag.current = false;
537
+ }, {
764
538
  once: true
765
539
  });
766
540
  }
@@ -927,12 +701,6 @@ function useDrawer(props) {
927
701
  const timeTaken = dragEndTime.current.getTime() - dragStartTime.current.getTime();
928
702
  const distMoved = pointerStart.current - (isVertical(direction) ? event.pageY : event.pageX);
929
703
  const velocity = Math.abs(distMoved) / timeTaken;
930
- if (velocity > 0.05) {
931
- setJustReleased(true);
932
- setTimeout(()=>{
933
- setJustReleased(false);
934
- }, 200);
935
- }
936
704
  if (snapPoints) {
937
705
  const directionMultiplier = direction === "bottom" || direction === "right" ? 1 : -1;
938
706
  onReleaseSnapPoints({
@@ -1020,7 +788,7 @@ function useDrawer(props) {
1020
788
  drawerRef.current.style.height = `${initialDrawerHeight.current}px`;
1021
789
  }
1022
790
  if (snapPoints && snapPoints.length > 0 && !keyboardIsOpen.current) {
1023
- drawerRef.current.style.bottom = `0px`;
791
+ drawerRef.current.style.bottom = "0px";
1024
792
  } else {
1025
793
  drawerRef.current.style.bottom = `${Math.max(diffFromInitial, 0)}px`;
1026
794
  }
@@ -1058,9 +826,8 @@ function useDrawer(props) {
1058
826
  setShouldOverlayAnimate(false);
1059
827
  }, TRANSITIONS.ENTER_DURATION * 1000);
1060
828
  return ()=>clearTimeout(timeoutId);
1061
- } else {
1062
- setShouldOverlayAnimate(false);
1063
829
  }
830
+ setShouldOverlayAnimate(false);
1064
831
  }, [
1065
832
  isOpen,
1066
833
  snapPoints,
@@ -1135,7 +902,7 @@ function useDrawerContext() {
1135
902
  }
1136
903
 
1137
904
  const DrawerRoot = (props)=>{
1138
- const { children, defaultOpen, dismissible, onOpenChange, modal } = props;
905
+ const { children, defaultOpen, dismissible, modal } = props;
1139
906
  const api = useDrawer(props);
1140
907
  return /*#__PURE__*/ jsx(DialogPrimitive.Root, {
1141
908
  defaultOpen: defaultOpen,
@@ -1148,7 +915,6 @@ const DrawerRoot = (props)=>{
1148
915
  api.closeDrawer(true);
1149
916
  }
1150
917
  api.setIsOpen(open);
1151
- onOpenChange?.(open);
1152
918
  },
1153
919
  modal: modal,
1154
920
  children: /*#__PURE__*/ jsx(DrawerProvider, {
@@ -1164,7 +930,8 @@ const DrawerPositioner = /*#__PURE__*/ forwardRef((props, ref)=>{
1164
930
  ref: ref,
1165
931
  ...props,
1166
932
  style: {
1167
- pointerEvents: api.isOpen ? undefined : "none"
933
+ pointerEvents: api.isOpen ? undefined : "none",
934
+ ...props.style
1168
935
  }
1169
936
  });
1170
937
  });