@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.
package/src/useDrawer.ts CHANGED
@@ -9,12 +9,11 @@ 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
- export interface DialogProps {
16
+ export interface UseDrawerProps {
18
17
  activeSnapPoint?: number | string | null;
19
18
  setActiveSnapPoint?: (snapPoint: number | string | null) => void;
20
19
  children?: React.ReactNode;
@@ -26,7 +25,8 @@ export interface DialogProps {
26
25
  */
27
26
  closeThreshold?: number;
28
27
  /**
29
- * When `true` the `body` doesn't get any styles assigned from Vaul
28
+ * When `true` the `body` doesn't get any styles assigned from Drawer
29
+ * @default true
30
30
  */
31
31
  noBodyStyles?: boolean;
32
32
  onOpenChange?: (open: boolean) => void;
@@ -46,7 +46,7 @@ export interface DialogProps {
46
46
  handleOnly?: boolean;
47
47
  /**
48
48
  * When `false` dragging, clicking outside, pressing esc, etc. will not close the drawer.
49
- * 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.
50
50
  * @default true
51
51
  */
52
52
  dismissible?: boolean;
@@ -69,11 +69,6 @@ export interface DialogProps {
69
69
  * @default false
70
70
  */
71
71
  defaultOpen?: boolean;
72
- /**
73
- * When set to `true` prevents scrolling on the document body on mount, and restores it on unmount.
74
- * @default false
75
- */
76
- disablePreventScroll?: boolean;
77
72
  /**
78
73
  * When `true` Vaul will reposition inputs rather than scroll then into view if the keyboard is in the way.
79
74
  * Setting it to `false` will fall back to the default browser behavior.
@@ -98,7 +93,7 @@ export interface DialogProps {
98
93
 
99
94
  /**
100
95
  * Array of snap points to use.
101
- * 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).
102
97
  * @default undefined
103
98
  */
104
99
  snapPoints?: (number | string)[];
@@ -123,7 +118,7 @@ export interface DialogProps {
123
118
  closeOnEscape?: boolean;
124
119
  }
125
120
 
126
- export function useDrawer(props: DialogProps) {
121
+ export function useDrawer(props: UseDrawerProps) {
127
122
  const {
128
123
  open: openProp,
129
124
  onOpenChange,
@@ -141,10 +136,9 @@ export function useDrawer(props: DialogProps) {
141
136
  modal = true,
142
137
  onClose,
143
138
  nested,
144
- noBodyStyles = false,
139
+ noBodyStyles = true,
145
140
  direction = "bottom",
146
141
  defaultOpen = false,
147
- disablePreventScroll = true,
148
142
  snapToSequentialPoint = false,
149
143
  preventScrollRestoration = false,
150
144
  repositionInputs = true,
@@ -185,7 +179,6 @@ export function useDrawer(props: DialogProps) {
185
179
 
186
180
  const [hasBeenOpened, setHasBeenOpened] = useState<boolean>(false);
187
181
  const [isDragging, setIsDragging] = useState<boolean>(false);
188
- const [justReleased, setJustReleased] = useState<boolean>(false);
189
182
  const [shouldOverlayAnimate, setShouldOverlayAnimate] = useState<boolean>(false);
190
183
 
191
184
  const overlayRef = useRef<HTMLDivElement>(null);
@@ -233,17 +226,6 @@ export function useDrawer(props: DialogProps) {
233
226
  snapToSequentialPoint,
234
227
  });
235
228
 
236
- usePreventScroll({
237
- isDisabled:
238
- !isOpen ||
239
- isDragging ||
240
- !modal ||
241
- justReleased ||
242
- !hasBeenOpened ||
243
- !repositionInputs ||
244
- !disablePreventScroll,
245
- });
246
-
247
229
  const { restorePositionSetting } = usePositionFixed({
248
230
  isOpen,
249
231
  modal,
@@ -263,7 +245,13 @@ export function useDrawer(props: DialogProps) {
263
245
  dragStartTime.current = new Date();
264
246
 
265
247
  if (isIOS()) {
266
- window.addEventListener("touchend", () => (isAllowedToDrag.current = false), { once: true });
248
+ window.addEventListener(
249
+ "touchend",
250
+ () => {
251
+ isAllowedToDrag.current = false;
252
+ },
253
+ { once: true },
254
+ );
267
255
  }
268
256
  (event.target as HTMLElement).setPointerCapture(event.pointerId);
269
257
 
@@ -495,13 +483,6 @@ export function useDrawer(props: DialogProps) {
495
483
  const distMoved = pointerStart.current - (isVertical(direction) ? event.pageY : event.pageX);
496
484
  const velocity = Math.abs(distMoved) / timeTaken;
497
485
 
498
- if (velocity > 0.05) {
499
- setJustReleased(true);
500
- setTimeout(() => {
501
- setJustReleased(false);
502
- }, 200);
503
- }
504
-
505
486
  if (snapPoints) {
506
487
  const directionMultiplier = direction === "bottom" || direction === "right" ? 1 : -1;
507
488
  onReleaseSnapPoints({
@@ -614,7 +595,7 @@ export function useDrawer(props: DialogProps) {
614
595
  }
615
596
 
616
597
  if (snapPoints && snapPoints.length > 0 && !keyboardIsOpen.current) {
617
- drawerRef.current.style.bottom = `0px`;
598
+ drawerRef.current.style.bottom = "0px";
618
599
  } else {
619
600
  drawerRef.current.style.bottom = `${Math.max(diffFromInitial, 0)}px`;
620
601
  }
@@ -648,9 +629,9 @@ export function useDrawer(props: DialogProps) {
648
629
  }, TRANSITIONS.ENTER_DURATION * 1000);
649
630
 
650
631
  return () => clearTimeout(timeoutId);
651
- } else {
652
- setShouldOverlayAnimate(false);
653
632
  }
633
+
634
+ setShouldOverlayAnimate(false);
654
635
  }, [isOpen, snapPoints, fadeFromIndex]);
655
636
 
656
637
  return useMemo(
@@ -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
- }