@seed-design/react-drawer 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,149 @@
1
+ // This code comes from https://github.com/emilkowalski/vaul/blob/main/src/use-position-fixed.ts
2
+
3
+ import React from "react";
4
+ import { isSafari } from "./browser";
5
+
6
+ let previousBodyPosition: Record<string, string> | null = null;
7
+
8
+ /**
9
+ * This hook is necessary to prevent buggy behavior on iOS devices (need to test on Android).
10
+ * I won't get into too much detail about what bugs it solves, but so far I've found that setting the body to `position: fixed` is the most reliable way to prevent those bugs.
11
+ * Issues that this hook solves:
12
+ * https://github.com/emilkowalski/vaul/issues/435
13
+ * https://github.com/emilkowalski/vaul/issues/433
14
+ * And more that I discovered, but were just not reported.
15
+ */
16
+
17
+ export function usePositionFixed({
18
+ isOpen,
19
+ modal,
20
+ nested,
21
+ hasBeenOpened,
22
+ preventScrollRestoration,
23
+ noBodyStyles,
24
+ }: {
25
+ isOpen: boolean;
26
+ modal: boolean;
27
+ nested: boolean;
28
+ hasBeenOpened: boolean;
29
+ preventScrollRestoration: boolean;
30
+ noBodyStyles: boolean;
31
+ }) {
32
+ const [activeUrl, setActiveUrl] = React.useState(() =>
33
+ typeof window !== "undefined" ? window.location.href : "",
34
+ );
35
+ const scrollPos = React.useRef(0);
36
+
37
+ const setPositionFixed = React.useCallback(() => {
38
+ // All browsers on iOS will return true here.
39
+ if (!isSafari()) return;
40
+
41
+ // If previousBodyPosition is already set, don't set it again.
42
+ if (previousBodyPosition === null && isOpen && !noBodyStyles) {
43
+ previousBodyPosition = {
44
+ position: document.body.style.position,
45
+ top: document.body.style.top,
46
+ left: document.body.style.left,
47
+ height: document.body.style.height,
48
+ right: "unset",
49
+ };
50
+
51
+ // Update the dom inside an animation frame
52
+ const { scrollX, innerHeight } = window;
53
+
54
+ document.body.style.setProperty("position", "fixed", "important");
55
+ Object.assign(document.body.style, {
56
+ top: `${-scrollPos.current}px`,
57
+ left: `${-scrollX}px`,
58
+ right: "0px",
59
+ height: "auto",
60
+ });
61
+
62
+ window.setTimeout(
63
+ () =>
64
+ window.requestAnimationFrame(() => {
65
+ // Attempt to check if the bottom bar appeared due to the position change
66
+ const bottomBarHeight = innerHeight - window.innerHeight;
67
+ if (bottomBarHeight && scrollPos.current >= innerHeight) {
68
+ // Move the content further up so that the bottom bar doesn't hide it
69
+ document.body.style.top = `${-(scrollPos.current + bottomBarHeight)}px`;
70
+ }
71
+ }),
72
+ 300,
73
+ );
74
+ }
75
+ }, [isOpen]);
76
+
77
+ const restorePositionSetting = React.useCallback(() => {
78
+ // All browsers on iOS will return true here.
79
+ if (!isSafari()) return;
80
+
81
+ if (previousBodyPosition !== null && !noBodyStyles) {
82
+ // Convert the position from "px" to Int
83
+ const y = -parseInt(document.body.style.top, 10);
84
+ const x = -parseInt(document.body.style.left, 10);
85
+
86
+ // Restore styles
87
+ Object.assign(document.body.style, previousBodyPosition);
88
+
89
+ window.requestAnimationFrame(() => {
90
+ if (preventScrollRestoration && activeUrl !== window.location.href) {
91
+ setActiveUrl(window.location.href);
92
+ return;
93
+ }
94
+
95
+ window.scrollTo(x, y);
96
+ });
97
+
98
+ previousBodyPosition = null;
99
+ }
100
+ }, [activeUrl]);
101
+
102
+ React.useEffect(() => {
103
+ function onScroll() {
104
+ scrollPos.current = window.scrollY;
105
+ }
106
+
107
+ onScroll();
108
+
109
+ window.addEventListener("scroll", onScroll);
110
+
111
+ return () => {
112
+ window.removeEventListener("scroll", onScroll);
113
+ };
114
+ }, []);
115
+
116
+ React.useEffect(() => {
117
+ if (!modal) return;
118
+
119
+ return () => {
120
+ if (typeof document === "undefined") return;
121
+
122
+ // Another drawer is opened, safe to ignore the execution
123
+ const hasDrawerOpened = !!document.querySelector("[data-drawer]");
124
+ if (hasDrawerOpened) return;
125
+
126
+ restorePositionSetting();
127
+ };
128
+ }, [modal, restorePositionSetting]);
129
+
130
+ React.useEffect(() => {
131
+ if (nested || !hasBeenOpened) return;
132
+ // This is needed to force Safari toolbar to show **before** the drawer starts animating to prevent a gnarly shift from happening
133
+ if (isOpen) {
134
+ // avoid for standalone mode (PWA)
135
+ const isStandalone = window.matchMedia("(display-mode: standalone)").matches;
136
+ !isStandalone && setPositionFixed();
137
+
138
+ if (!modal) {
139
+ window.setTimeout(() => {
140
+ restorePositionSetting();
141
+ }, 500);
142
+ }
143
+ } else {
144
+ restorePositionSetting();
145
+ }
146
+ }, [isOpen, hasBeenOpened, activeUrl, modal, nested, setPositionFixed, restorePositionSetting]);
147
+
148
+ return { restorePositionSetting };
149
+ }
@@ -0,0 +1,309 @@
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
+ }