@react-aria/overlays 3.29.0 → 3.30.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.
@@ -10,7 +10,7 @@
10
10
  * governing permissions and limitations under the License.
11
11
  */
12
12
 
13
- import {chain, getScrollParent, isIOS, useLayoutEffect} from '@react-aria/utils';
13
+ import {chain, getScrollParent, isIOS, isScrollable, useLayoutEffect, willOpenKeyboard} from '@react-aria/utils';
14
14
 
15
15
  interface PreventScrollOptions {
16
16
  /** Whether the scroll lock is disabled. */
@@ -19,19 +19,6 @@ interface PreventScrollOptions {
19
19
 
20
20
  const visualViewport = typeof document !== 'undefined' && window.visualViewport;
21
21
 
22
- // HTML input types that do not cause the software keyboard to appear.
23
- const nonTextInputTypes = new Set([
24
- 'checkbox',
25
- 'radio',
26
- 'range',
27
- 'color',
28
- 'file',
29
- 'image',
30
- 'button',
31
- 'submit',
32
- 'reset'
33
- ]);
34
-
35
22
  // The number of active usePreventScroll calls. Used to determine whether to revert back to the original page style/scroll position
36
23
  let preventScrollCount = 0;
37
24
  let restore;
@@ -98,35 +85,57 @@ function preventScrollStandard() {
98
85
  // on the window.
99
86
  // 2. Set `overscroll-behavior: contain` on nested scrollable regions so they do not scroll the page when at
100
87
  // the top or bottom. Work around a bug where this does not work when the element does not actually overflow
101
- // by preventing default in a `touchmove` event.
88
+ // by preventing default in a `touchmove` event. This is best effort: we can't prevent default when pinch
89
+ // zooming or when an element contains text selection, which may allow scrolling in some cases.
102
90
  // 3. Prevent default on `touchend` events on input elements and handle focusing the element ourselves.
103
- // 4. When focusing an input, apply a transform to trick Safari into thinking the input is at the top
104
- // of the page, which prevents it from scrolling the page. After the input is focused, scroll the element
105
- // into view ourselves, without scrolling the whole page.
106
- // 5. Offset the body by the scroll position using a negative margin and scroll to the top. This should appear the
107
- // same visually, but makes the actual scroll position always zero. This is required to make all of the
108
- // above work or Safari will still try to scroll the page when focusing an input.
109
- // 6. As a last resort, handle window scroll events, and scroll back to the top. This can happen when attempting
110
- // to navigate to an input with the next/previous buttons that's outside a modal.
91
+ // 4. When focus moves to an input, create an off screen input and focus that temporarily. This prevents
92
+ // Safari from scrolling the page. After a small delay, focus the real input and scroll it into view
93
+ // ourselves, without scrolling the whole page.
111
94
  function preventScrollMobileSafari() {
112
95
  let scrollable: Element;
113
- let restoreScrollableStyles;
96
+ let allowTouchMove = false;
114
97
  let onTouchStart = (e: TouchEvent) => {
115
98
  // Store the nearest scrollable parent element from the element that the user touched.
116
- scrollable = getScrollParent(e.target as Element, true);
117
- if (scrollable === document.documentElement && scrollable === document.body) {
118
- return;
99
+ let target = e.target as Element;
100
+ scrollable = isScrollable(target) ? target : getScrollParent(target, true);
101
+ allowTouchMove = false;
102
+
103
+ // If the target is selected, don't preventDefault in touchmove to allow user to adjust selection.
104
+ let selection = target.ownerDocument.defaultView!.getSelection();
105
+ if (selection && !selection.isCollapsed && selection.containsNode(target, true)) {
106
+ allowTouchMove = true;
119
107
  }
120
108
 
121
- // Prevent scrolling up when at the top and scrolling down when at the bottom
122
- // of a nested scrollable area, otherwise mobile Safari will start scrolling
123
- // the window instead.
124
- if (scrollable instanceof HTMLElement && window.getComputedStyle(scrollable).overscrollBehavior === 'auto') {
125
- restoreScrollableStyles = setStyle(scrollable, 'overscrollBehavior', 'contain');
109
+ // If this is a focused input element with a selected range, allow user to drag the selection handles.
110
+ if (
111
+ 'selectionStart' in target &&
112
+ 'selectionEnd' in target &&
113
+ (target.selectionStart as number) < (target.selectionEnd as number) &&
114
+ target.ownerDocument.activeElement === target
115
+ ) {
116
+ allowTouchMove = true;
126
117
  }
127
118
  };
128
119
 
120
+ // Prevent scrolling up when at the top and scrolling down when at the bottom
121
+ // of a nested scrollable area, otherwise mobile Safari will start scrolling
122
+ // the window instead.
123
+ // This must be applied before the touchstart event as of iOS 26, so inject it as a <style> element.
124
+ let style = document.createElement('style');
125
+ style.textContent = `
126
+ @layer {
127
+ * {
128
+ overscroll-behavior: contain;
129
+ }
130
+ }`.trim();
131
+ document.head.prepend(style);
132
+
129
133
  let onTouchMove = (e: TouchEvent) => {
134
+ // Allow pinch-zooming.
135
+ if (e.touches.length === 2 || allowTouchMove) {
136
+ return;
137
+ }
138
+
130
139
  // Prevent scrolling the window.
131
140
  if (!scrollable || scrollable === document.documentElement || scrollable === document.body) {
132
141
  e.preventDefault();
@@ -144,86 +153,48 @@ function preventScrollMobileSafari() {
144
153
  }
145
154
  };
146
155
 
147
- let onTouchEnd = () => {
148
- if (restoreScrollableStyles) {
149
- restoreScrollableStyles();
150
- }
151
- };
152
-
153
- let onFocus = (e: FocusEvent) => {
156
+ let onBlur = (e: FocusEvent) => {
154
157
  let target = e.target as HTMLElement;
155
- if (willOpenKeyboard(target)) {
156
- setupStyles();
157
-
158
- // Apply a transform to trick Safari into thinking the input is at the top of the page
159
- // so it doesn't try to scroll it into view.
160
- target.style.transform = 'translateY(-2000px)';
161
- requestAnimationFrame(() => {
162
- target.style.transform = '';
163
-
164
- // This will have prevented the browser from scrolling the focused element into view,
165
- // so we need to do this ourselves in a way that doesn't cause the whole page to scroll.
166
- if (visualViewport) {
167
- if (visualViewport.height < window.innerHeight) {
168
- // If the keyboard is already visible, do this after one additional frame
169
- // to wait for the transform to be removed.
170
- requestAnimationFrame(() => {
171
- scrollIntoView(target);
172
- });
173
- } else {
174
- // Otherwise, wait for the visual viewport to resize before scrolling so we can
175
- // measure the correct position to scroll to.
176
- visualViewport.addEventListener('resize', () => scrollIntoView(target), {once: true});
177
- }
178
- }
179
- });
158
+ let relatedTarget = e.relatedTarget as HTMLElement | null;
159
+ if (relatedTarget && willOpenKeyboard(relatedTarget)) {
160
+ // Focus without scrolling the whole page, and then scroll into view manually.
161
+ relatedTarget.focus({preventScroll: true});
162
+ scrollIntoViewWhenReady(relatedTarget, willOpenKeyboard(target));
163
+ } else if (!relatedTarget) {
164
+ // When tapping the Done button on the keyboard, focus moves to the body.
165
+ // FocusScope will then restore focus back to the input. Later when tapping
166
+ // the same input again, it is already focused, so no blur event will fire,
167
+ // resulting in the flow above never running and Safari's native scrolling occurring.
168
+ // Instead, move focus to the parent focusable element (e.g. the dialog).
169
+ let focusable = target.parentElement?.closest('[tabindex]') as HTMLElement | null;
170
+ focusable?.focus({preventScroll: true});
180
171
  }
181
172
  };
182
173
 
183
- let restoreStyles: null | (() => void) = null;
184
- let setupStyles = () => {
185
- if (restoreStyles) {
186
- return;
187
- }
188
-
189
- let onWindowScroll = () => {
190
- // Last resort. If the window scrolled, scroll it back to the top.
191
- // It should always be at the top because the body will have a negative margin (see below).
192
- window.scrollTo(0, 0);
193
- };
194
-
195
- // Record the original scroll position so we can restore it.
196
- // Then apply a negative margin to the body to offset it by the scroll position. This will
197
- // enable us to scroll the window to the top, which is required for the rest of this to work.
198
- let scrollX = window.pageXOffset;
199
- let scrollY = window.pageYOffset;
174
+ // Override programmatic focus to scroll into view without scrolling the whole page.
175
+ let focus = HTMLElement.prototype.focus;
176
+ HTMLElement.prototype.focus = function (opts) {
177
+ // Track whether the keyboard was already visible before.
178
+ let wasKeyboardVisible = document.activeElement != null && willOpenKeyboard(document.activeElement);
200
179
 
201
- restoreStyles = chain(
202
- addEvent(window, 'scroll', onWindowScroll),
203
- setStyle(document.documentElement, 'paddingRight', `${window.innerWidth - document.documentElement.clientWidth}px`),
204
- setStyle(document.documentElement, 'overflow', 'hidden'),
205
- setStyle(document.body, 'marginTop', `-${scrollY}px`),
206
- () => {
207
- window.scrollTo(scrollX, scrollY);
208
- }
209
- );
180
+ // Focus the element without scrolling the page.
181
+ focus.call(this, {...opts, preventScroll: true});
210
182
 
211
- // Scroll to the top. The negative margin on the body will make this appear the same.
212
- window.scrollTo(0, 0);
183
+ if (!opts || !opts.preventScroll) {
184
+ scrollIntoViewWhenReady(this, wasKeyboardVisible);
185
+ }
213
186
  };
214
187
 
215
188
  let removeEvents = chain(
216
189
  addEvent(document, 'touchstart', onTouchStart, {passive: false, capture: true}),
217
190
  addEvent(document, 'touchmove', onTouchMove, {passive: false, capture: true}),
218
- addEvent(document, 'touchend', onTouchEnd, {passive: false, capture: true}),
219
- addEvent(document, 'focus', onFocus, true)
191
+ addEvent(document, 'blur', onBlur, true)
220
192
  );
221
193
 
222
194
  return () => {
223
- // Restore styles and scroll the page back to where it was.
224
- restoreScrollableStyles?.();
225
- restoreStyles?.();
226
195
  removeEvents();
196
+ style.remove();
197
+ HTMLElement.prototype.focus = focus;
227
198
  };
228
199
  }
229
200
 
@@ -253,6 +224,17 @@ function addEvent<K extends keyof GlobalEventHandlersEventMap>(
253
224
  };
254
225
  }
255
226
 
227
+ function scrollIntoViewWhenReady(target: Element, wasKeyboardVisible: boolean) {
228
+ if (wasKeyboardVisible || !visualViewport) {
229
+ // If the keyboard was already visible, scroll the target into view immediately.
230
+ scrollIntoView(target);
231
+ } else {
232
+ // Otherwise, wait for the visual viewport to resize before scrolling so we can
233
+ // measure the correct position to scroll to.
234
+ visualViewport.addEventListener('resize', () => scrollIntoView(target), {once: true});
235
+ }
236
+ }
237
+
256
238
  function scrollIntoView(target: Element) {
257
239
  let root = document.scrollingElement || document.documentElement;
258
240
  let nextTarget: Element | null = target;
@@ -260,21 +242,24 @@ function scrollIntoView(target: Element) {
260
242
  // Find the parent scrollable element and adjust the scroll position if the target is not already in view.
261
243
  let scrollable = getScrollParent(nextTarget);
262
244
  if (scrollable !== document.documentElement && scrollable !== document.body && scrollable !== nextTarget) {
263
- let scrollableTop = scrollable.getBoundingClientRect().top;
264
- let targetTop = nextTarget.getBoundingClientRect().top;
265
- if (targetTop > scrollableTop + nextTarget.clientHeight) {
266
- scrollable.scrollTop += targetTop - scrollableTop;
245
+ let scrollableRect = scrollable.getBoundingClientRect();
246
+ let targetRect = nextTarget.getBoundingClientRect();
247
+ if (targetRect.top < scrollableRect.top || targetRect.bottom > scrollableRect.top + nextTarget.clientHeight) {
248
+ let bottom = scrollableRect.bottom;
249
+ if (visualViewport) {
250
+ bottom = Math.min(bottom, visualViewport.offsetTop + visualViewport.height);
251
+ }
252
+
253
+ // Center within the viewport.
254
+ let adjustment = (targetRect.top - scrollableRect.top) - ((bottom - scrollableRect.top) / 2 - targetRect.height / 2);
255
+ scrollable.scrollTo({
256
+ // Clamp to the valid range to prevent over-scrolling.
257
+ top: Math.max(0, Math.min(scrollable.scrollHeight - scrollable.clientHeight, scrollable.scrollTop + adjustment)),
258
+ behavior: 'smooth'
259
+ });
267
260
  }
268
261
  }
269
262
 
270
263
  nextTarget = scrollable.parentElement;
271
264
  }
272
265
  }
273
-
274
- function willOpenKeyboard(target: Element) {
275
- return (
276
- (target instanceof HTMLInputElement && !nonTextInputTypes.has(target.type)) ||
277
- target instanceof HTMLTextAreaElement ||
278
- (target instanceof HTMLElement && target.isContentEditable)
279
- );
280
- }