Skip to content

Commit 98fc4dd

Browse files
Leo Rossijelbourn
Leo Rossi
authored andcommitted
This defect was already fixed in PR #12624 but this one is going to be merge into 6.4.X.
* Fixes the position of flexible overlays with pushing enabled being thrown off once the user starts scrolling. * Fixes flexible overlays with pushing not handling locked positioning. With these changes locked overlays will only be pushed when they're opened, whereas non-locked overlays will stay in the viewport, even when the user scrolls down. * Fixes a potential issue due to a couple of variables being initialized together where one is set to zero and the other one is undefined. Fixes #11365.
1 parent eccd28b commit 98fc4dd

File tree

4 files changed

+187
-22
lines changed

4 files changed

+187
-22
lines changed

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

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

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

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

+52-21
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);
@@ -152,7 +155,13 @@ export class FlexibleConnectedPositionStrategy implements PositionStrategy {
152155
this._boundingBox = overlayRef.hostElement;
153156
this._pane = overlayRef.overlayElement;
154157
this._resizeSubscription.unsubscribe();
155-
this._resizeSubscription = this._viewportRuler.change().subscribe(() => this.apply());
158+
this._resizeSubscription = this._viewportRuler.change().subscribe(() => {
159+
// When the window is resized, we want to trigger the next reposition as if it
160+
// was an initial render, in order for the strategy to pick a new optimal position,
161+
// otherwise position locking will cause it to stay at the old one.
162+
this._isInitialRender = true;
163+
this.apply();
164+
});
156165
}
157166

158167
/**
@@ -282,6 +291,8 @@ export class FlexibleConnectedPositionStrategy implements PositionStrategy {
282291
}
283292

284293
detach() {
294+
this._lastPosition = null;
295+
this._previousPushAmount = null;
285296
this._resizeSubscription.unsubscribe();
286297
}
287298

@@ -541,39 +552,54 @@ export class FlexibleConnectedPositionStrategy implements PositionStrategy {
541552
* the viewport, the top-left corner will be pushed on-screen (with overflow occuring on the
542553
* right and bottom).
543554
*
544-
* @param start The starting point from which the overlay is pushed.
545-
* @param overlay The overlay dimensions.
555+
* @param start Starting point from which the overlay is pushed.
556+
* @param overlay Dimensions of the overlay.
557+
* @param scrollPosition Current viewport scroll position.
546558
* @returns The point at which to position the overlay after pushing. This is effectively a new
547559
* originPoint.
548560
*/
549-
private _pushOverlayOnScreen(start: Point, overlay: ClientRect): Point {
561+
private _pushOverlayOnScreen(start: Point,
562+
overlay: ClientRect,
563+
scrollPosition: ViewportScrollPosition): Point {
564+
// If the position is locked and we've pushed the overlay already, reuse the previous push
565+
// amount, rather than pushing it again. If we were to continue pushing, the element would
566+
// remain in the viewport, which goes against the expectations when position locking is enabled.
567+
if (this._previousPushAmount && this._positionLocked) {
568+
return {
569+
x: start.x + this._previousPushAmount.x,
570+
y: start.y + this._previousPushAmount.y
571+
};
572+
}
550573
const viewport = this._viewportRect;
551574

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.
575+
// Determine how much the overlay goes outside the viewport on each
576+
// side, which we'll use to decide which direction to push it.
554577
const overflowRight = Math.max(start.x + overlay.width - viewport.right, 0);
555578
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);
579+
const overflowTop = Math.max(viewport.top - scrollPosition.top - start.y, 0);
580+
const overflowLeft = Math.max(viewport.left - scrollPosition.left - start.x, 0);
558581

559-
// Amount by which to push the overlay in each direction such that it remains on-screen.
560-
let pushX, pushY = 0;
582+
// Amount by which to push the overlay in each axis such that it remains on-screen.
583+
let pushX = 0;
584+
let pushY = 0;
561585

562586
// If the overlay fits completely within the bounds of the viewport, push it from whichever
563587
// direction is goes off-screen. Otherwise, push the top-left corner such that its in the
564588
// viewport and allow for the trailing end of the overlay to go out of bounds.
565-
if (overlay.width <= viewport.width) {
589+
if (overlay.width < viewport.width) {
566590
pushX = overflowLeft || -overflowRight;
567591
} else {
568-
pushX = viewport.left - start.x;
592+
pushX = start.x < this._viewportMargin ? (viewport.left - scrollPosition.left) - start.x : 0;
569593
}
570594

571-
if (overlay.height <= viewport.height) {
595+
if (overlay.height < viewport.height) {
572596
pushY = overflowTop || -overflowBottom;
573597
} else {
574-
pushY = viewport.top - start.y;
598+
pushY = start.y < this._viewportMargin ? (viewport.top - scrollPosition.top) - start.y : 0;
575599
}
576600

601+
this._previousPushAmount = {x: pushX, y: pushY};
602+
577603
return {
578604
x: start.x + pushX,
579605
y: start.y + pushY,
@@ -792,8 +818,9 @@ export class FlexibleConnectedPositionStrategy implements PositionStrategy {
792818
const styles = {} as CSSStyleDeclaration;
793819

794820
if (this._hasExactPosition()) {
795-
extendStyles(styles, this._getExactOverlayY(position, originPoint));
796-
extendStyles(styles, this._getExactOverlayX(position, originPoint));
821+
const scrollPosition = this._viewportRuler.getViewportScrollPosition();
822+
extendStyles(styles, this._getExactOverlayY(position, originPoint, scrollPosition));
823+
extendStyles(styles, this._getExactOverlayX(position, originPoint, scrollPosition));
797824
} else {
798825
styles.position = 'static';
799826
}
@@ -832,14 +859,16 @@ export class FlexibleConnectedPositionStrategy implements PositionStrategy {
832859
}
833860

834861
/** Gets the exact top/bottom for the overlay when not using flexible sizing or when pushing. */
835-
private _getExactOverlayY(position: ConnectedPosition, originPoint: Point) {
862+
private _getExactOverlayY(position: ConnectedPosition,
863+
originPoint: Point,
864+
scrollPosition: ViewportScrollPosition) {
836865
// Reset any existing styles. This is necessary in case the
837866
// preferred position has changed since the last `apply`.
838867
let styles = {top: null, bottom: null} as CSSStyleDeclaration;
839868
let overlayPoint = this._getOverlayPoint(originPoint, this._overlayRect, position);
840869

841870
if (this._isPushed) {
842-
overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect);
871+
overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect, scrollPosition);
843872
}
844873

845874
// @breaking-change 7.0.0 Currently the `_overlayContainer` is optional in order to avoid a
@@ -869,14 +898,16 @@ export class FlexibleConnectedPositionStrategy implements PositionStrategy {
869898
}
870899

871900
/** Gets the exact left/right for the overlay when not using flexible sizing or when pushing. */
872-
private _getExactOverlayX(position: ConnectedPosition, originPoint: Point) {
901+
private _getExactOverlayX(position: ConnectedPosition,
902+
originPoint: Point,
903+
scrollPosition: ViewportScrollPosition) {
873904
// Reset any existing styles. This is necessary in case the preferred position has
874905
// changed since the last `apply`.
875906
let styles = {left: null, right: null} as CSSStyleDeclaration;
876907
let overlayPoint = this._getOverlayPoint(originPoint, this._overlayRect, position);
877908

878909
if (this._isPushed) {
879-
overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect);
910+
overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect, scrollPosition);
880911
}
881912

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

src/cdk/scrolling/viewport-ruler.ts

+7-1
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

+1
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,7 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy {
360360
return new OverlayConfig({
361361
positionStrategy: this._overlay.position()
362362
.flexibleConnectedTo(this._element)
363+
.withLockedPosition()
363364
.withTransformOriginOn('.mat-menu-panel'),
364365
hasBackdrop: this.menu.hasBackdrop == null ? !this.triggersSubmenu() : this.menu.hasBackdrop,
365366
backdropClass: this.menu.backdropClass || 'cdk-overlay-transparent-backdrop',

0 commit comments

Comments
 (0)