@react-aria/overlays 3.29.1 → 3.31.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.
@@ -103,14 +103,18 @@ const TOTAL_SIZE = {
103
103
 
104
104
  const PARSED_PLACEMENT_CACHE = {};
105
105
 
106
- let visualViewport = typeof document !== 'undefined' ? window.visualViewport : null;
106
+ let getVisualViewport = () => typeof document !== 'undefined' ? window.visualViewport : null;
107
107
 
108
- function getContainerDimensions(containerNode: Element): Dimensions {
108
+ function getContainerDimensions(containerNode: Element, visualViewport: VisualViewport | null): Dimensions {
109
109
  let width = 0, height = 0, totalWidth = 0, totalHeight = 0, top = 0, left = 0;
110
110
  let scroll: Position = {};
111
111
  let isPinchZoomedIn = (visualViewport?.scale ?? 1) > 1;
112
112
 
113
- if (containerNode.tagName === 'BODY') {
113
+ // In the case where the container is `html` or `body` and the container doesn't have something like `position: relative`,
114
+ // then position absolute will be positioned relative to the viewport, also known as the `initial containing block`.
115
+ // That's why we use the visual viewport instead.
116
+
117
+ if (containerNode.tagName === 'BODY' || containerNode.tagName === 'HTML') {
114
118
  let documentElement = document.documentElement;
115
119
  totalWidth = documentElement.clientWidth;
116
120
  totalHeight = documentElement.clientHeight;
@@ -179,10 +183,13 @@ function getDelta(
179
183
  let boundarySize = boundaryDimensions[AXIS_SIZE[axis]];
180
184
  // Calculate the edges of the boundary (accomodating for the boundary padding) and the edges of the overlay.
181
185
  // Note that these values are with respect to the visual viewport (aka 0,0 is the top left of the viewport)
182
- let boundaryStartEdge = boundaryDimensions.scroll[AXIS[axis]] + padding;
183
- let boundaryEndEdge = boundarySize + boundaryDimensions.scroll[AXIS[axis]] - padding;
184
- let startEdgeOffset = offset - containerScroll + containerOffsetWithBoundary[axis] - boundaryDimensions[AXIS[axis]];
185
- let endEdgeOffset = offset - containerScroll + size + containerOffsetWithBoundary[axis] - boundaryDimensions[AXIS[axis]];
186
+
187
+ let boundaryStartEdge = containerOffsetWithBoundary[axis] + boundaryDimensions.scroll[AXIS[axis]] + padding;
188
+ let boundaryEndEdge = containerOffsetWithBoundary[axis] + boundaryDimensions.scroll[AXIS[axis]] + boundarySize - padding;
189
+ // transformed value of the left edge of the overlay
190
+ let startEdgeOffset = offset - containerScroll + boundaryDimensions.scroll[AXIS[axis]] + containerOffsetWithBoundary[axis] - boundaryDimensions[AXIS[axis]];
191
+ // transformed value of the right edge of the overlay
192
+ let endEdgeOffset = offset - containerScroll + size + boundaryDimensions.scroll[AXIS[axis]] + containerOffsetWithBoundary[axis] - boundaryDimensions[AXIS[axis]];
186
193
 
187
194
  // If any of the overlay edges falls outside of the boundary, shift the overlay the required amount to align one of the overlay's
188
195
  // edges with the closest boundary edge.
@@ -234,7 +241,8 @@ function computePosition(
234
241
  containerOffsetWithBoundary: Offset,
235
242
  isContainerPositioned: boolean,
236
243
  arrowSize: number,
237
- arrowBoundaryOffset: number
244
+ arrowBoundaryOffset: number,
245
+ containerDimensions: Dimensions
238
246
  ) {
239
247
  let {placement, crossPlacement, axis, crossAxis, size, crossSize} = placementInfo;
240
248
  let position: Position = {};
@@ -255,9 +263,9 @@ function computePosition(
255
263
 
256
264
  position[crossAxis]! += crossOffset;
257
265
 
258
- // overlay top overlapping arrow with button bottom
266
+ // overlay top or left overlapping arrow with button bottom or right
259
267
  const minPosition = childOffset[crossAxis] - overlaySize[crossSize] + arrowSize + arrowBoundaryOffset;
260
- // overlay bottom overlapping arrow with button top
268
+ // overlay bottom or right overlapping arrow with button top or left
261
269
  const maxPosition = childOffset[crossAxis] + childOffset[crossSize] - arrowSize - arrowBoundaryOffset;
262
270
  position[crossAxis] = clamp(position[crossAxis]!, minPosition, maxPosition);
263
271
 
@@ -266,8 +274,8 @@ function computePosition(
266
274
  // If the container is positioned (non-static), then we use the container's actual
267
275
  // height, as `bottom` will be relative to this height. But if the container is static,
268
276
  // then it can only be the `document.body`, and `bottom` will be relative to _its_
269
- // container, which should be as large as boundaryDimensions.
270
- const containerHeight = (isContainerPositioned ? containerOffsetWithBoundary[size] : boundaryDimensions[TOTAL_SIZE[size]]);
277
+ // container.
278
+ let containerHeight = (isContainerPositioned ? containerDimensions[size] : containerDimensions[TOTAL_SIZE[size]]);
271
279
  position[FLIPPED_DIRECTION[axis]] = Math.floor(containerHeight - childOffset[axis] + offset);
272
280
  } else {
273
281
  position[axis] = Math.floor(childOffset[axis] + childOffset[size] + offset);
@@ -283,42 +291,72 @@ function getMaxHeight(
283
291
  margins: Position,
284
292
  padding: number,
285
293
  overlayHeight: number,
286
- heightGrowthDirection: HeightGrowthDirection
294
+ heightGrowthDirection: HeightGrowthDirection,
295
+ containerDimensions: Dimensions,
296
+ isContainerDescendentOfBoundary: boolean,
297
+ visualViewport: VisualViewport | null
287
298
  ) {
288
- const containerHeight = (isContainerPositioned ? containerOffsetWithBoundary.height : boundaryDimensions[TOTAL_SIZE.height]);
289
- // For cases where position is set via "bottom" instead of "top", we need to calculate the true overlay top with respect to the boundary. Reverse calculate this with the same method
290
- // used in computePosition.
291
- let overlayTop = position.top != null ? containerOffsetWithBoundary.top + position.top : containerOffsetWithBoundary.top + (containerHeight - (position.bottom ?? 0) - overlayHeight);
299
+ // For cases where position is set via "bottom" instead of "top", we need to calculate the true overlay top
300
+ // with respect to the container.
301
+ let overlayTop = (position.top != null ? position.top : (containerDimensions[TOTAL_SIZE.height] - (position.bottom ?? 0) - overlayHeight)) - (containerDimensions.scroll.top ?? 0);
302
+ // calculate the dimentions of the "boundingRect" which is most restrictive top/bottom of the boundaryRect and the visual view port
303
+ let boundaryToContainerTransformOffset = isContainerDescendentOfBoundary ? containerOffsetWithBoundary.top : 0;
304
+ let boundingRect = {
305
+ // This should be boundary top in container coord system vs viewport top in container coord system
306
+ // For the viewport top, there are several cases
307
+ // 1. pinchzoom case where we want the viewports offset top as top here
308
+ // 2. case where container is offset from the boundary and is contained by the boundary. In this case the top we want here is NOT 0, we want to take boundary's top even though is is a negative number OR the visual viewport, whichever is more restrictive
309
+ top: Math.max(boundaryDimensions.top + boundaryToContainerTransformOffset, (visualViewport?.offsetTop ?? boundaryDimensions.top) + boundaryToContainerTransformOffset),
310
+ bottom: Math.min((boundaryDimensions.top + boundaryDimensions.height + boundaryToContainerTransformOffset), (visualViewport?.offsetTop ?? 0) + (visualViewport?.height ?? 0))
311
+ };
312
+
292
313
  let maxHeight = heightGrowthDirection !== 'top' ?
293
314
  // We want the distance between the top of the overlay to the bottom of the boundary
294
315
  Math.max(0,
295
- (boundaryDimensions.height + boundaryDimensions.top + (boundaryDimensions.scroll.top ?? 0)) // this is the bottom of the boundary
316
+ boundingRect.bottom // this is the bottom of the boundary
296
317
  - overlayTop // this is the top of the overlay
297
318
  - ((margins.top ?? 0) + (margins.bottom ?? 0) + padding) // save additional space for margin and padding
298
319
  )
299
320
  // We want the distance between the bottom of the overlay to the top of the boundary
300
321
  : Math.max(0,
301
322
  (overlayTop + overlayHeight) // this is the bottom of the overlay
302
- - (boundaryDimensions.top + (boundaryDimensions.scroll.top ?? 0)) // this is the top of the boundary
323
+ - boundingRect.top // this is the top of the boundary
303
324
  - ((margins.top ?? 0) + (margins.bottom ?? 0) + padding) // save additional space for margin and padding
304
325
  );
305
- return Math.min(boundaryDimensions.height - (padding * 2), maxHeight);
326
+ return maxHeight;
306
327
  }
307
328
 
308
329
  function getAvailableSpace(
309
- boundaryDimensions: Dimensions,
330
+ boundaryDimensions: Dimensions, // boundary
310
331
  containerOffsetWithBoundary: Offset,
311
- childOffset: Offset,
312
- margins: Position,
313
- padding: number,
314
- placementInfo: ParsedPlacement
332
+ childOffset: Offset, // trigger, position based of container's non-viewport 0,0
333
+ margins: Position, // overlay
334
+ padding: number, // overlay <-> boundary
335
+ placementInfo: ParsedPlacement,
336
+ containerDimensions: Dimensions,
337
+ isContainerDescendentOfBoundary: boolean
315
338
  ) {
316
339
  let {placement, axis, size} = placementInfo;
317
340
  if (placement === axis) {
318
- return Math.max(0, childOffset[axis] - boundaryDimensions[axis] - (boundaryDimensions.scroll[axis] ?? 0) + containerOffsetWithBoundary[axis] - (margins[axis] ?? 0) - margins[FLIPPED_DIRECTION[axis]] - padding);
341
+ return Math.max(0,
342
+ childOffset[axis] // trigger start
343
+ - (containerDimensions.scroll[axis] ?? 0) // transform trigger position to be with respect to viewport 0,0
344
+ - (boundaryDimensions[axis] + (isContainerDescendentOfBoundary ? containerOffsetWithBoundary[axis] : 0)) // boundary start
345
+ - (margins[axis] ?? 0) // margins usually for arrows or other decorations
346
+ - margins[FLIPPED_DIRECTION[axis]]
347
+ - padding); // padding between overlay and boundary
319
348
  }
320
349
 
321
- return Math.max(0, boundaryDimensions[size] + boundaryDimensions[axis] + boundaryDimensions.scroll[axis] - containerOffsetWithBoundary[axis] - childOffset[axis] - childOffset[size] - (margins[axis] ?? 0) - margins[FLIPPED_DIRECTION[axis]] - padding);
350
+ return Math.max(0,
351
+ (boundaryDimensions[size]
352
+ + boundaryDimensions[axis]
353
+ + (isContainerDescendentOfBoundary ? containerOffsetWithBoundary[axis] : 0))
354
+ - childOffset[axis]
355
+ - childOffset[size]
356
+ + (containerDimensions.scroll[axis] ?? 0)
357
+ - (margins[axis] ?? 0)
358
+ - margins[FLIPPED_DIRECTION[axis]]
359
+ - padding);
322
360
  }
323
361
 
324
362
  export function calculatePositionInternal(
@@ -337,11 +375,13 @@ export function calculatePositionInternal(
337
375
  isContainerPositioned: boolean,
338
376
  userSetMaxHeight: number | undefined,
339
377
  arrowSize: number,
340
- arrowBoundaryOffset: number
378
+ arrowBoundaryOffset: number,
379
+ isContainerDescendentOfBoundary: boolean,
380
+ visualViewport: VisualViewport | null
341
381
  ): PositionResult {
342
382
  let placementInfo = parsePlacement(placementInput);
343
383
  let {size, crossAxis, crossSize, placement, crossPlacement} = placementInfo;
344
- let position = computePosition(childOffset, boundaryDimensions, overlaySize, placementInfo, offset, crossOffset, containerOffsetWithBoundary, isContainerPositioned, arrowSize, arrowBoundaryOffset);
384
+ let position = computePosition(childOffset, boundaryDimensions, overlaySize, placementInfo, offset, crossOffset, containerOffsetWithBoundary, isContainerPositioned, arrowSize, arrowBoundaryOffset, containerDimensions);
345
385
  let normalizedOffset = offset;
346
386
  let space = getAvailableSpace(
347
387
  boundaryDimensions,
@@ -349,20 +389,25 @@ export function calculatePositionInternal(
349
389
  childOffset,
350
390
  margins,
351
391
  padding + offset,
352
- placementInfo
392
+ placementInfo,
393
+ containerDimensions,
394
+ isContainerDescendentOfBoundary
353
395
  );
354
396
 
355
397
  // Check if the scroll size of the overlay is greater than the available space to determine if we need to flip
356
- if (flip && scrollSize[size] > space) {
398
+ if (flip && overlaySize[size] > space) {
357
399
  let flippedPlacementInfo = parsePlacement(`${FLIPPED_DIRECTION[placement]} ${crossPlacement}` as Placement);
358
- let flippedPosition = computePosition(childOffset, boundaryDimensions, overlaySize, flippedPlacementInfo, offset, crossOffset, containerOffsetWithBoundary, isContainerPositioned, arrowSize, arrowBoundaryOffset);
400
+ let flippedPosition = computePosition(childOffset, boundaryDimensions, overlaySize, flippedPlacementInfo, offset, crossOffset, containerOffsetWithBoundary, isContainerPositioned, arrowSize, arrowBoundaryOffset, containerDimensions);
401
+
359
402
  let flippedSpace = getAvailableSpace(
360
403
  boundaryDimensions,
361
404
  containerOffsetWithBoundary,
362
405
  childOffset,
363
406
  margins,
364
407
  padding + offset,
365
- flippedPlacementInfo
408
+ flippedPlacementInfo,
409
+ containerDimensions,
410
+ isContainerDescendentOfBoundary
366
411
  );
367
412
 
368
413
  // If the available space for the flipped position is greater than the original available space, flip.
@@ -400,7 +445,10 @@ export function calculatePositionInternal(
400
445
  margins,
401
446
  padding,
402
447
  overlaySize.height,
403
- heightGrowthDirection
448
+ heightGrowthDirection,
449
+ containerDimensions,
450
+ isContainerDescendentOfBoundary,
451
+ visualViewport
404
452
  );
405
453
 
406
454
  if (userSetMaxHeight && userSetMaxHeight < maxHeight) {
@@ -409,7 +457,7 @@ export function calculatePositionInternal(
409
457
 
410
458
  overlaySize.height = Math.min(overlaySize.height, maxHeight);
411
459
 
412
- position = computePosition(childOffset, boundaryDimensions, overlaySize, placementInfo, normalizedOffset, crossOffset, containerOffsetWithBoundary, isContainerPositioned, arrowSize, arrowBoundaryOffset);
460
+ position = computePosition(childOffset, boundaryDimensions, overlaySize, placementInfo, normalizedOffset, crossOffset, containerOffsetWithBoundary, isContainerPositioned, arrowSize, arrowBoundaryOffset, containerDimensions);
413
461
  delta = getDelta(crossAxis, position[crossAxis]!, overlaySize[crossSize], boundaryDimensions, containerDimensions, padding, containerOffsetWithBoundary);
414
462
  position[crossAxis]! += delta;
415
463
 
@@ -484,6 +532,7 @@ export function calculatePosition(opts: PositionOpts): PositionResult {
484
532
  arrowBoundaryOffset = 0
485
533
  } = opts;
486
534
 
535
+ let visualViewport = getVisualViewport();
487
536
  let container = overlayNode instanceof HTMLElement ? getContainingBlock(overlayNode) : document.documentElement;
488
537
  let isViewportContainer = container === document.documentElement;
489
538
  const containerPositionStyle = window.getComputedStyle(container).position;
@@ -502,17 +551,19 @@ export function calculatePosition(opts: PositionOpts): PositionResult {
502
551
  overlaySize.height += (margins.top ?? 0) + (margins.bottom ?? 0);
503
552
 
504
553
  let scrollSize = getScroll(scrollNode);
505
- let boundaryDimensions = getContainerDimensions(boundaryElement);
506
- let containerDimensions = getContainerDimensions(container);
554
+
555
+ // Note that due to logic inside getContainerDimensions, for cases where the boundary element is the body, we will return
556
+ // a height/width that matches the visual viewport size rather than the body's height/width (aka for zoom it will be zoom adjusted size)
557
+ // and a top/left that is adjusted as well (will return the top/left of the zoomed in viewport, or 0,0 for a non-zoomed body)
558
+ // Otherwise this returns the height/width of a arbitrary boundary element, and its top/left with respect to the viewport (NOTE THIS MEANS IT DOESNT INCLUDE SCROLL)
559
+ let boundaryDimensions = getContainerDimensions(boundaryElement, visualViewport);
560
+ let containerDimensions = getContainerDimensions(container, visualViewport);
507
561
  // If the container is the HTML element wrapping the body element, the retrieved scrollTop/scrollLeft will be equal to the
508
562
  // body element's scroll. Set the container's scroll values to 0 since the overlay's edge position value in getDelta don't then need to be further offset
509
563
  // by the container scroll since they are essentially the same containing element and thus in the same coordinate system
510
- let containerOffsetWithBoundary: Offset = boundaryElement.tagName === 'BODY' ? getOffset(container, false) : getPosition(container, boundaryElement, false);
511
- if (container.tagName === 'HTML' && boundaryElement.tagName === 'BODY') {
512
- containerDimensions.scroll.top = 0;
513
- containerDimensions.scroll.left = 0;
514
- }
564
+ let containerOffsetWithBoundary: Offset = getPosition(boundaryElement, container, false);
515
565
 
566
+ let isContainerDescendentOfBoundary = boundaryElement.contains(container);
516
567
  return calculatePositionInternal(
517
568
  placement,
518
569
  childOffset,
@@ -529,14 +580,16 @@ export function calculatePosition(opts: PositionOpts): PositionResult {
529
580
  isContainerPositioned,
530
581
  maxHeight,
531
582
  arrowSize,
532
- arrowBoundaryOffset
583
+ arrowBoundaryOffset,
584
+ isContainerDescendentOfBoundary,
585
+ visualViewport
533
586
  );
534
587
  }
535
588
 
536
589
  export function getRect(node: Element, ignoreScale: boolean) {
537
590
  let {top, left, width, height} = node.getBoundingClientRect();
538
591
 
539
- // Use offsetWidth and offsetHeight if this is an HTML element, so that
592
+ // Use offsetWidth and offsetHeight if this is an HTML element, so that
540
593
  // the size is not affected by scale transforms.
541
594
  if (ignoreScale && node instanceof node.ownerDocument.defaultView!.HTMLElement) {
542
595
  width = node.offsetWidth;
@@ -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
- }