Skip to content

Commit a192907

Browse files
crisbetojosephperrott
authored andcommitted
fix(overlay): flexible overlay with push not handling scroll offset and position locking (#11628)
1 parent cb3f760 commit a192907

File tree

4 files changed

+213
-21
lines changed

4 files changed

+213
-21
lines changed

src/cdk/overlay/position/flexible-connected-position-strategy.spec.ts

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1134,6 +1134,165 @@ describe('FlexibleConnectedPositionStrategy', () => {
11341134
expect(Math.floor(overlayRect.top)).toBe(15);
11351135
});
11361136

1137+
it('should not mess with the left offset when pushing from the top', () => {
1138+
originElement.style.top = `${-OVERLAY_HEIGHT * 2}px`;
1139+
originElement.style.left = '200px';
1140+
1141+
positionStrategy.withPositions([{
1142+
originX: 'start',
1143+
originY: 'bottom',
1144+
overlayX: 'start',
1145+
overlayY: 'top'
1146+
}]);
1147+
1148+
attachOverlay({positionStrategy});
1149+
1150+
const overlayRect = overlayRef.overlayElement.getBoundingClientRect();
1151+
expect(Math.floor(overlayRect.left)).toBe(200);
1152+
});
1153+
1154+
it('should align to the trigger if the overlay is wider than the viewport, but the trigger ' +
1155+
'is still within the viewport', () => {
1156+
originElement.style.top = '200px';
1157+
originElement.style.left = '200px';
1158+
1159+
positionStrategy.withPositions([
1160+
{
1161+
originX: 'start',
1162+
originY: 'bottom',
1163+
overlayX: 'start',
1164+
overlayY: 'top'
1165+
},
1166+
{
1167+
originX: 'end',
1168+
originY: 'bottom',
1169+
overlayX: 'end',
1170+
overlayY: 'top'
1171+
}
1172+
]);
1173+
1174+
attachOverlay({
1175+
width: viewport.getViewportRect().width + 100,
1176+
positionStrategy
1177+
});
1178+
1179+
const overlayRect = overlayRef.overlayElement.getBoundingClientRect();
1180+
const originRect = originElement.getBoundingClientRect();
1181+
1182+
expect(Math.floor(overlayRect.left)).toBe(Math.floor(originRect.left));
1183+
});
1184+
1185+
it('should push into the viewport if the overlay is wider than the viewport and the trigger' +
1186+
'out of the viewport', () => {
1187+
originElement.style.top = '200px';
1188+
originElement.style.left = `-${DEFAULT_WIDTH / 2}px`;
1189+
1190+
positionStrategy.withPositions([
1191+
{
1192+
originX: 'start',
1193+
originY: 'bottom',
1194+
overlayX: 'start',
1195+
overlayY: 'top'
1196+
},
1197+
{
1198+
originX: 'end',
1199+
originY: 'bottom',
1200+
overlayX: 'end',
1201+
overlayY: 'top'
1202+
}
1203+
]);
1204+
1205+
attachOverlay({
1206+
width: viewport.getViewportRect().width + 100,
1207+
positionStrategy
1208+
});
1209+
1210+
const overlayRect = overlayRef.overlayElement.getBoundingClientRect();
1211+
expect(Math.floor(overlayRect.left)).toBe(0);
1212+
});
1213+
1214+
it('should keep the element inside the viewport as the user is scrolling, ' +
1215+
'with position locking disabled', () => {
1216+
const veryLargeElement = document.createElement('div');
1217+
1218+
originElement.style.top = `${-OVERLAY_HEIGHT * 2}px`;
1219+
originElement.style.left = '200px';
1220+
1221+
veryLargeElement.style.width = '100%';
1222+
veryLargeElement.style.height = '2000px';
1223+
document.body.appendChild(veryLargeElement);
1224+
1225+
positionStrategy
1226+
.withLockedPosition(false)
1227+
.withViewportMargin(0)
1228+
.withPositions([{
1229+
overlayY: 'top',
1230+
overlayX: 'start',
1231+
originY: 'top',
1232+
originX: 'start'
1233+
}]);
1234+
1235+
attachOverlay({positionStrategy});
1236+
1237+
let overlayRect = overlayRef.overlayElement.getBoundingClientRect();
1238+
expect(Math.floor(overlayRect.top))
1239+
.toBe(0, 'Expected overlay to be in the viewport initially.');
1240+
1241+
window.scroll(0, 100);
1242+
overlayRef.updatePosition();
1243+
zone.simulateZoneExit();
1244+
1245+
overlayRect = overlayRef.overlayElement.getBoundingClientRect();
1246+
expect(Math.floor(overlayRect.top))
1247+
.toBe(0, 'Expected overlay to stay in the viewport after scrolling.');
1248+
1249+
window.scroll(0, 0);
1250+
document.body.removeChild(veryLargeElement);
1251+
});
1252+
1253+
it('should not continue pushing the overlay as the user scrolls, if position ' +
1254+
'locking is enabled', () => {
1255+
const veryLargeElement = document.createElement('div');
1256+
1257+
originElement.style.top = `${-OVERLAY_HEIGHT * 2}px`;
1258+
originElement.style.left = '200px';
1259+
1260+
veryLargeElement.style.width = '100%';
1261+
veryLargeElement.style.height = '2000px';
1262+
document.body.appendChild(veryLargeElement);
1263+
1264+
positionStrategy
1265+
.withLockedPosition()
1266+
.withViewportMargin(0)
1267+
.withPositions([{
1268+
overlayY: 'top',
1269+
overlayX: 'start',
1270+
originY: 'top',
1271+
originX: 'start'
1272+
}]);
1273+
1274+
attachOverlay({positionStrategy});
1275+
1276+
const scrollBy = 100;
1277+
let initialOverlayTop = Math.floor(overlayRef.overlayElement.getBoundingClientRect().top);
1278+
1279+
expect(initialOverlayTop).toBe(0, 'Expected overlay to be inside the viewport initially.');
1280+
1281+
window.scroll(0, scrollBy);
1282+
overlayRef.updatePosition();
1283+
zone.simulateZoneExit();
1284+
1285+
let currentOverlayTop = Math.floor(overlayRef.overlayElement.getBoundingClientRect().top);
1286+
1287+
expect(currentOverlayTop).toBeLessThan(0,
1288+
'Expected overlay to no longer be completely inside the viewport.');
1289+
expect(currentOverlayTop).toBe(initialOverlayTop - scrollBy,
1290+
'Expected overlay to maintain its previous position.');
1291+
1292+
window.scroll(0, 0);
1293+
document.body.removeChild(veryLargeElement);
1294+
});
1295+
11371296
});
11381297

11391298
describe('with flexible dimensions', () => {

src/cdk/overlay/position/flexible-connected-position-strategy.ts

Lines changed: 46 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
import {PositionStrategy} from './position-strategy';
1010
import {ElementRef} from '@angular/core';
11-
import {ViewportRuler, CdkScrollable} from '@angular/cdk/scrolling';
11+
import {ViewportRuler, CdkScrollable, ViewportScrollPosition} from '@angular/cdk/scrolling';
1212
import {
1313
ConnectedOverlayPositionChange,
1414
ConnectionPositionPair,
@@ -112,6 +112,9 @@ export class FlexibleConnectedPositionStrategy implements PositionStrategy {
112112
/** Amount of subscribers to the `positionChanges` stream. */
113113
private _positionChangeSubscriptions = 0;
114114

115+
/** Amount by which the overlay was pushed in each axis during the last time it was positioned. */
116+
private _previousPushAmount: {x: number, y: number} | null;
117+
115118
/** Observable sequence of position changes. */
116119
positionChanges: Observable<ConnectedOverlayPositionChange> = Observable.create(observer => {
117120
const subscription = this._positionChanges.subscribe(observer);
@@ -282,6 +285,8 @@ export class FlexibleConnectedPositionStrategy implements PositionStrategy {
282285
}
283286

284287
detach() {
288+
this._lastPosition = null;
289+
this._previousPushAmount = null;
285290
this._resizeSubscription.unsubscribe();
286291
}
287292

@@ -541,39 +546,55 @@ export class FlexibleConnectedPositionStrategy implements PositionStrategy {
541546
* the viewport, the top-left corner will be pushed on-screen (with overflow occuring on the
542547
* right and bottom).
543548
*
544-
* @param start The starting point from which the overlay is pushed.
545-
* @param overlay The overlay dimensions.
549+
* @param start Starting point from which the overlay is pushed.
550+
* @param overlay Dimensions of the overlay.
551+
* @param scrollPosition Current viewport scroll position.
546552
* @returns The point at which to position the overlay after pushing. This is effectively a new
547553
* originPoint.
548554
*/
549-
private _pushOverlayOnScreen(start: Point, overlay: ClientRect): Point {
555+
private _pushOverlayOnScreen(start: Point,
556+
overlay: ClientRect,
557+
scrollPosition: ViewportScrollPosition): Point {
558+
// If the position is locked and we've pushed the overlay already, reuse the previous push
559+
// amount, rather than pushing it again. If we were to continue pushing, the element would
560+
// remain in the viewport, which goes against the expectations when position locking is enabled.
561+
if (this._previousPushAmount && this._positionLocked) {
562+
return {
563+
x: start.x + this._previousPushAmount.x,
564+
y: start.y + this._previousPushAmount.y
565+
};
566+
}
567+
550568
const viewport = this._viewportRect;
551569

552-
// Determine how much the overlay goes outside the viewport on each side, which we'll use to
553-
// decide which direction to push it.
570+
// Determine how much the overlay goes outside the viewport on each
571+
// side, which we'll use to decide which direction to push it.
554572
const overflowRight = Math.max(start.x + overlay.width - viewport.right, 0);
555573
const overflowBottom = Math.max(start.y + overlay.height - viewport.bottom, 0);
556-
const overflowTop = Math.max(viewport.top - start.y, 0);
557-
const overflowLeft = Math.max(viewport.left - start.x, 0);
574+
const overflowTop = Math.max(viewport.top - scrollPosition.top - start.y, 0);
575+
const overflowLeft = Math.max(viewport.left - scrollPosition.left - start.x, 0);
558576

559-
// Amount by which to push the overlay in each direction such that it remains on-screen.
560-
let pushX, pushY = 0;
577+
// Amount by which to push the overlay in each axis such that it remains on-screen.
578+
let pushX = 0;
579+
let pushY = 0;
561580

562581
// If the overlay fits completely within the bounds of the viewport, push it from whichever
563582
// direction is goes off-screen. Otherwise, push the top-left corner such that its in the
564583
// viewport and allow for the trailing end of the overlay to go out of bounds.
565-
if (overlay.width <= viewport.width) {
584+
if (overlay.width < viewport.width) {
566585
pushX = overflowLeft || -overflowRight;
567586
} else {
568-
pushX = viewport.left - start.x;
587+
pushX = start.x < this._viewportMargin ? (viewport.left - scrollPosition.left) - start.x : 0;
569588
}
570589

571-
if (overlay.height <= viewport.height) {
590+
if (overlay.height < viewport.height) {
572591
pushY = overflowTop || -overflowBottom;
573592
} else {
574-
pushY = viewport.top - start.y;
593+
pushY = start.y < this._viewportMargin ? (viewport.top - scrollPosition.top) - start.y : 0;
575594
}
576595

596+
this._previousPushAmount = {x: pushX, y: pushY};
597+
577598
return {
578599
x: start.x + pushX,
579600
y: start.y + pushY,
@@ -792,8 +813,9 @@ export class FlexibleConnectedPositionStrategy implements PositionStrategy {
792813
const styles = {} as CSSStyleDeclaration;
793814

794815
if (this._hasExactPosition()) {
795-
extendStyles(styles, this._getExactOverlayY(position, originPoint));
796-
extendStyles(styles, this._getExactOverlayX(position, originPoint));
816+
const scrollPosition = this._viewportRuler.getViewportScrollPosition();
817+
extendStyles(styles, this._getExactOverlayY(position, originPoint, scrollPosition));
818+
extendStyles(styles, this._getExactOverlayX(position, originPoint, scrollPosition));
797819
} else {
798820
styles.position = 'static';
799821
}
@@ -832,14 +854,16 @@ export class FlexibleConnectedPositionStrategy implements PositionStrategy {
832854
}
833855

834856
/** Gets the exact top/bottom for the overlay when not using flexible sizing or when pushing. */
835-
private _getExactOverlayY(position: ConnectedPosition, originPoint: Point) {
857+
private _getExactOverlayY(position: ConnectedPosition,
858+
originPoint: Point,
859+
scrollPosition: ViewportScrollPosition) {
836860
// Reset any existing styles. This is necessary in case the
837861
// preferred position has changed since the last `apply`.
838862
let styles = {top: null, bottom: null} as CSSStyleDeclaration;
839863
let overlayPoint = this._getOverlayPoint(originPoint, this._overlayRect, position);
840864

841865
if (this._isPushed) {
842-
overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect);
866+
overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect, scrollPosition);
843867
}
844868

845869
// @breaking-change 7.0.0 Currently the `_overlayContainer` is optional in order to avoid a
@@ -869,14 +893,16 @@ export class FlexibleConnectedPositionStrategy implements PositionStrategy {
869893
}
870894

871895
/** Gets the exact left/right for the overlay when not using flexible sizing or when pushing. */
872-
private _getExactOverlayX(position: ConnectedPosition, originPoint: Point) {
896+
private _getExactOverlayX(position: ConnectedPosition,
897+
originPoint: Point,
898+
scrollPosition: ViewportScrollPosition) {
873899
// Reset any existing styles. This is necessary in case the preferred position has
874900
// changed since the last `apply`.
875901
let styles = {left: null, right: null} as CSSStyleDeclaration;
876902
let overlayPoint = this._getOverlayPoint(originPoint, this._overlayRect, position);
877903

878904
if (this._isPushed) {
879-
overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect);
905+
overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect, scrollPosition);
880906
}
881907

882908
// We want to set either `left` or `right` based on whether the overlay wants to appear "before"

src/cdk/scrolling/viewport-ruler.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,12 @@ import {auditTime} from 'rxjs/operators';
1414
/** Time in ms to throttle the resize events by default. */
1515
export const DEFAULT_RESIZE_TIME = 20;
1616

17+
/** Object that holds the scroll position of the viewport in each direction. */
18+
export interface ViewportScrollPosition {
19+
top: number;
20+
left: number;
21+
}
22+
1723
/**
1824
* Simple utility for getting the bounds of the browser viewport.
1925
* @docs-private
@@ -82,7 +88,7 @@ export class ViewportRuler implements OnDestroy {
8288
}
8389

8490
/** Gets the (top, left) scroll position of the viewport. */
85-
getViewportScrollPosition() {
91+
getViewportScrollPosition(): ViewportScrollPosition {
8692
// While we can get a reference to the fake document
8793
// during SSR, it doesn't have getBoundingClientRect.
8894
if (!this._platform.isBrowser) {

src/lib/menu/menu-trigger.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,7 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy {
358358
return new OverlayConfig({
359359
positionStrategy: this._overlay.position()
360360
.flexibleConnectedTo(this._element)
361+
.withLockedPosition()
361362
.withTransformOriginOn('.mat-menu-panel'),
362363
hasBackdrop: this.menu.hasBackdrop == null ? !this.triggersSubmenu() : this.menu.hasBackdrop,
363364
backdropClass: this.menu.backdropClass || 'cdk-overlay-transparent-backdrop',

0 commit comments

Comments
 (0)