This repository has been archived by the owner on Sep 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 78
/
flexible-connected-position-strategy.ts
1430 lines (1228 loc) · 48.5 KB
/
flexible-connected-position-strategy.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2020 Dynatrace LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* This is a temporary solution to get a workaround of a missing feature of Angular Materials
* `FlexibleConnectedPositionStrategy` that we can add a viewport boundary for the top and left
* edges where the overlay should not push in.
*
* In our case it is especially needed to avoid positioning the overlay above the page ribbon in the cluster.
*
* TODO: Try to contribute this feature to the material library
*/
// tslint:disable
import { coerceArray, coerceCssPixelValue } from '@angular/cdk/coercion';
import { OverlayContainer, PositionStrategy } from '@angular/cdk/overlay';
import { Platform } from '@angular/cdk/platform';
import {
CdkScrollable,
ViewportRuler,
ViewportScrollPosition,
} from '@angular/cdk/scrolling';
import { ElementRef } from '@angular/core';
import { Observable, Subject, Subscription } from 'rxjs';
import {
ConnectedOverlayPositionChange,
ConnectionPositionPair,
ScrollingVisibility,
validateHorizontalPosition,
validateVerticalPosition,
} from './connected-position';
import { OverlayReference } from './overlay-reference';
import {
isElementClippedByScrolling,
isElementScrolledOutsideView,
} from './scroll-clip';
// TODO: refactor clipping detection into a separate thing (part of scrolling module)
// TODO: doesn't handle both flexible width and height when it has to scroll along both axis.
/** Class to be added to the overlay bounding box. */
const boundingBoxClass = 'cdk-overlay-connected-position-bounding-box';
/** Possible values that can be set as the origin of a FlexibleConnectedPositionStrategy. */
export type FlexibleConnectedPositionStrategyOrigin =
| ElementRef
| HTMLElement
| (Point & {
width?: number;
height?: number;
});
/**
* A strategy for positioning overlays. Using this strategy, an overlay is given an
* implicit position relative some origin element. The relative position is defined in terms of
* a point on the origin element that is connected to a point on the overlay element. For example,
* a basic dropdown is connecting the bottom-left corner of the origin to the top-left corner
* of the overlay.
*/
export class DtFlexibleConnectedPositionStrategy implements PositionStrategy {
/** The overlay to which this strategy is attached. */
private _overlayRef: OverlayReference;
/** Whether we're performing the very first positioning of the overlay. */
private _isInitialRender: boolean;
/** Last size used for the bounding box. Used to avoid resizing the overlay after open. */
private _lastBoundingBoxSize = { width: 0, height: 0 };
/** Whether the overlay was pushed out of the viewport */
private _isOutsideViewport = false;
/** Whether the overlay was pushed in a previous positioning. */
private _isPushed = false;
/** Whether the overlay can be pushed on-screen on the initial open. */
private _canPush = true;
/** Whether the overlay can grow via flexible width/height after the initial open. */
private _growAfterOpen = false;
/** Whether the overlay's width and height can be constrained to fit within the viewport. */
private _hasFlexibleDimensions = true;
/** Whether the overlay position is locked. */
private _positionLocked = false;
/** Cached origin dimensions */
private _originRect: ClientRect;
/** Cached overlay dimensions */
private _overlayRect: ClientRect;
/** Cached viewport dimensions */
private _viewportRect: ClientRect;
/** Amount of space that must be maintained between the overlay and the edge of the viewport. */
private _viewportMargin = 0;
/** The margin between the overlay and the viewport top and left edges in pixels. */
private _viewportBoundaries: ViewportBoundaries = { top: 0, left: 0 };
/** The Scrollable containers used to check scrollable view properties on position change. */
private _scrollables: CdkScrollable[] = [];
/** @internal Ordered list of preferred positions, from most to least desirable. */
_preferredPositions: ConnectionPositionPair[] = [];
/** The origin element against which the overlay will be positioned. */
private _origin: FlexibleConnectedPositionStrategyOrigin;
/** The overlay pane element. */
private _pane: HTMLElement;
/** Whether the strategy has been disposed of already. */
private _isDisposed: boolean;
/**
* Parent element for the overlay panel used to constrain the overlay panel's size to fit
* within the viewport.
*/
private _boundingBox: HTMLElement | null;
/** The last position to have been calculated as the best fit position. */
private _lastPosition: ConnectedPosition | null;
/** Subject that emits whenever the position changes. */
private _positionChanges = new Subject<ConnectedOverlayPositionChange>();
/** Subscription to viewport size changes. */
private _resizeSubscription = Subscription.EMPTY;
/** Default offset for the overlay along the x axis. */
private _offsetX = 0;
/** Default offset for the overlay along the y axis. */
private _offsetY = 0;
/** Selector to be used when finding the elements on which to set the transform origin. */
private _transformOriginSelector: string;
/** Keeps track of the CSS classes that the position strategy has applied on the overlay panel. */
private _appliedPanelClasses: string[] = [];
/** Amount by which the overlay was pushed in each axis during the last time it was positioned. */
private _previousPushAmount: { x: number; y: number } | null;
/** Observable sequence of position changes. */
positionChanges: Observable<
ConnectedOverlayPositionChange
> = this._positionChanges.asObservable();
/** Ordered list of preferred positions, from most to least desirable. */
get positions(): ConnectionPositionPair[] {
return this._preferredPositions;
}
constructor(
connectedTo: FlexibleConnectedPositionStrategyOrigin,
private _viewportRuler: ViewportRuler,
private _document: Document,
private _platform: Platform,
private _overlayContainer: OverlayContainer,
) {
this.setOrigin(connectedTo);
}
/** Attaches this position strategy to an overlay. */
attach(overlayRef: OverlayReference): void {
if (this._overlayRef && overlayRef !== this._overlayRef) {
throw Error('This position strategy is already attached to an overlay');
}
this._validatePositions();
overlayRef.hostElement.classList.add(boundingBoxClass);
this._overlayRef = overlayRef;
this._boundingBox = overlayRef.hostElement;
this._pane = overlayRef.overlayElement;
this._isDisposed = false;
this._isInitialRender = true;
this._lastPosition = null;
this._resizeSubscription.unsubscribe();
this._resizeSubscription = this._viewportRuler.change().subscribe(() => {
// When the window is resized, we want to trigger the next reposition as if it
// was an initial render, in order for the strategy to pick a new optimal position,
// otherwise position locking will cause it to stay at the old one.
this._isInitialRender = true;
this.apply();
});
}
/**
* Updates the position of the overlay element, using whichever preferred position relative
* to the origin best fits on-screen.
*
* The selection of a position goes as follows:
* - If any positions fit completely within the viewport as-is,
* choose the first position that does so.
* - If flexible dimensions are enabled and at least one satifies the given minimum width/height,
* choose the position with the greatest available size modified by the positions' weight.
* - If pushing is enabled, take the position that went off-screen the least and push it
* on-screen.
* - If none of the previous criteria were met, use the position that goes off-screen the least.
* @docs-private
*/
apply(): void {
// We shouldn't do anything if the strategy was disposed or we're on the server.
if (this._isDisposed || !this._platform.isBrowser) {
return;
}
// If the position has been applied already (e.g. when the overlay was opened) and the
// consumer opted into locking in the position, re-use the old position, in order to
// prevent the overlay from jumping around.
if (!this._isInitialRender && this._positionLocked && this._lastPosition) {
this.reapplyLastPosition();
return;
}
this._clearPanelClasses();
this._resetOverlayElementStyles();
this._resetBoundingBoxStyles();
// We need the bounding rects for the origin and the overlay to determine how to position
// the overlay relative to the origin.
// We use the viewport rect to determine whether a position would go off-screen.
this._viewportRect = this._getNarrowedViewportRect();
this._originRect = this._getOriginRect();
this._overlayRect = this._pane.getBoundingClientRect();
const originRect = this._originRect;
const overlayRect = this._overlayRect;
const viewportRect = this._viewportRect;
// Positions where the overlay will fit with flexible dimensions.
const flexibleFits: FlexibleFit[] = [];
// Fallback if none of the preferred positions fit within the viewport.
let fallback: FallbackPosition | undefined;
// Go through each of the preferred positions looking for a good fit.
// If a good fit is found, it will be applied immediately.
for (const pos of this._preferredPositions) {
// Get the exact (x, y) coordinate for the point-of-origin on the origin element.
const originPoint = this._getOriginPoint(originRect, pos);
// From that point-of-origin, get the exact (x, y) coordinate for the top-left corner of the
// overlay in this position. We use the top-left corner for calculations and later translate
// this into an appropriate (top, left, bottom, right) style.
const overlayPoint = this._getOverlayPoint(originPoint, overlayRect, pos);
// Calculate how well the overlay would fit into the viewport with this point.
const overlayFit = this._getOverlayFit(
overlayPoint,
overlayRect,
viewportRect,
pos,
);
// If the overlay, without any further work, fits into the viewport, use this position.
if (overlayFit.isCompletelyWithinViewport) {
this._isPushed = false;
this._applyPosition(pos, originPoint);
return;
}
// If the overlay has flexible dimensions, we can use this position
// so long as there's enough space for the minimum dimensions.
if (
this._canFitWithFlexibleDimensions(
overlayFit,
overlayPoint,
viewportRect,
)
) {
// Save positions where the overlay will fit with flexible dimensions. We will use these
// if none of the positions fit *without* flexible dimensions.
flexibleFits.push({
position: pos,
origin: originPoint,
overlayRect,
boundingBoxRect: this._calculateBoundingBoxRect(originPoint, pos),
});
continue;
}
// If the current preferred position does not fit on the screen, remember the position
// if it has more visible area on-screen than we've seen and move onto the next preferred
// position.
if (
!fallback ||
fallback.overlayFit.visibleArea < overlayFit.visibleArea
) {
fallback = {
overlayFit,
overlayPoint,
originPoint,
position: pos,
overlayRect,
};
}
}
// If there are any positions where the overlay would fit with flexible dimensions, choose the
// one that has the greatest area available modified by the position's weight
if (flexibleFits.length) {
let bestFit: FlexibleFit | null = null;
let bestScore = -1;
for (const fit of flexibleFits) {
const score =
fit.boundingBoxRect.width *
fit.boundingBoxRect.height *
(fit.position.weight || 1);
if (score > bestScore) {
bestScore = score;
bestFit = fit;
}
}
this._isPushed = false;
this._applyPosition(bestFit!.position, bestFit!.origin);
return;
}
// When none of the preferred positions fit within the viewport, take the position
// that went off-screen the least and attempt to push it on-screen.
if (this._canPush) {
// TODO(jelbourn): after pushing, the opening "direction" of the overlay might not make sense.
this._isPushed = true;
this._applyPosition(fallback!.position, fallback!.originPoint);
return;
}
this._hideOverlay();
// All options for getting the overlay within the viewport have been exhausted, so go with the
// position that went off-screen the least.
// this._applyPosition(fallback!.position, fallback!.originPoint);
}
detach(): void {
this._clearPanelClasses();
this._lastPosition = null;
this._previousPushAmount = null;
this._resizeSubscription.unsubscribe();
}
/** Cleanup after the element gets destroyed. */
dispose(): void {
if (this._isDisposed) {
return;
}
// We can't use `_resetBoundingBoxStyles` here, because it resets
// some properties to zero, rather than removing them.
if (this._boundingBox) {
extendStyles(this._boundingBox.style, {
top: '',
left: '',
right: '',
bottom: '',
height: '',
width: '',
alignItems: '',
justifyContent: '',
display: '',
} as CSSStyleDeclaration);
}
if (this._pane) {
this._resetOverlayElementStyles();
}
if (this._overlayRef) {
this._overlayRef.hostElement.classList.remove(boundingBoxClass);
}
this.detach();
this._positionChanges.complete();
this._overlayRef = this._boundingBox = null!;
this._isDisposed = true;
}
/**
* This re-aligns the overlay element with the trigger in its last calculated position,
* even if a position higher in the "preferred positions" list would now fit. This
* allows one to re-align the panel without changing the orientation of the panel.
*/
reapplyLastPosition(): void {
if (!this._isDisposed && (!this._platform || this._platform.isBrowser)) {
this._originRect = this._getOriginRect();
this._overlayRect = this._pane.getBoundingClientRect();
this._viewportRect = this._getNarrowedViewportRect();
const lastPosition = this._lastPosition || this._preferredPositions[0];
const originPoint = this._getOriginPoint(this._originRect, lastPosition);
this._applyPosition(lastPosition, originPoint);
}
}
/**
* Sets the list of Scrollable containers that host the origin element so that
* on reposition we can evaluate if it or the overlay has been clipped or outside view. Every
* Scrollable must be an ancestor element of the strategy's origin element.
*/
withScrollableContainers(scrollables: CdkScrollable[]): this {
this._scrollables = scrollables;
return this;
}
/**
* Adds new preferred positions.
* @param positions List of positions options for this overlay.
*/
withPositions(positions: ConnectedPosition[]): this {
this._preferredPositions = positions;
// If the last calculated position object isn't part of the positions anymore, clear
// it in order to avoid it being picked up if the consumer tries to re-apply.
if (positions.indexOf(this._lastPosition!) === -1) {
this._lastPosition = null;
}
this._validatePositions();
return this;
}
/**
* Sets a minimum distance the overlay may be positioned to the edge of the viewport.
* @param margin Required margin between the overlay and the viewport edge in pixels.
*/
withViewportMargin(margin: number): this {
this._viewportMargin = margin;
return this;
}
/**
* Sets a boundary to the edge of the viewport in which the overlay wont be positioned
* @param boundaries Required margin between the overlay and the viewport top and left edges in pixels.
*/
withViewportBoundaries(boundaries: ViewportBoundaries): this {
this._viewportBoundaries = boundaries;
return this;
}
/** Sets whether the overlay's width and height can be constrained to fit within the viewport. */
withFlexibleDimensions(flexibleDimensions = true): this {
this._hasFlexibleDimensions = flexibleDimensions;
return this;
}
/** Sets whether the overlay can grow after the initial open via flexible width/height. */
withGrowAfterOpen(growAfterOpen = true): this {
this._growAfterOpen = growAfterOpen;
return this;
}
/** Sets whether the overlay can be pushed on-screen if none of the provided positions fit. */
withPush(canPush = true): this {
this._canPush = canPush;
return this;
}
/**
* Sets whether the overlay's position should be locked in after it is positioned
* initially. When an overlay is locked in, it won't attempt to reposition itself
* when the position is re-applied (e.g. when the user scrolls away).
* @param isLocked Whether the overlay should locked in.
*/
withLockedPosition(isLocked = true): this {
this._positionLocked = isLocked;
return this;
}
/**
* Sets the origin, relative to which to position the overlay.
* Using an element origin is useful for building components that need to be positioned
* relatively to a trigger (e.g. dropdown menus or tooltips), whereas using a point can be
* used for cases like contextual menus which open relative to the user's pointer.
* @param origin Reference to the new origin.
*/
setOrigin(origin: FlexibleConnectedPositionStrategyOrigin): this {
this._origin = origin;
return this;
}
/**
* Sets the default offset for the overlay's connection point on the x-axis.
* @param offset New offset in the X axis.
*/
withDefaultOffsetX(offset: number): this {
this._offsetX = offset;
return this;
}
/**
* Sets the default offset for the overlay's connection point on the y-axis.
* @param offset New offset in the Y axis.
*/
withDefaultOffsetY(offset: number): this {
this._offsetY = offset;
return this;
}
/**
* Configures that the position strategy should set a `transform-origin` on some elements
* inside the overlay, depending on the current position that is being applied. This is
* useful for the cases where the origin of an animation can change depending on the
* alignment of the overlay.
* @param selector CSS selector that will be used to find the target
* elements onto which to set the transform origin.
*/
withTransformOriginOn(selector: string): this {
this._transformOriginSelector = selector;
return this;
}
/**
* Gets the (x, y) coordinate of a connection point on the origin based on a relative position.
*/
private _getOriginPoint(
originRect: ClientRect,
pos: ConnectedPosition,
): Point {
let x: number;
if (pos.originX == 'center') {
// Note: when centering we should always use the `left`
// offset, otherwise the position will be wrong in RTL.
x = originRect.left + originRect.width / 2;
} else {
const startX = this._isRtl() ? originRect.right : originRect.left;
const endX = this._isRtl() ? originRect.left : originRect.right;
x = pos.originX == 'start' ? startX : endX;
}
let y: number;
if (pos.originY == 'center') {
y = originRect.top + originRect.height / 2;
} else {
y = pos.originY == 'top' ? originRect.top : originRect.bottom;
}
return { x, y };
}
/**
* Gets the (x, y) coordinate of the top-left corner of the overlay given a given position and
* origin point to which the overlay should be connected.
*/
private _getOverlayPoint(
originPoint: Point,
overlayRect: ClientRect,
pos: ConnectedPosition,
): Point {
// Calculate the (overlayStartX, overlayStartY), the start of the
// potential overlay position relative to the origin point.
let overlayStartX: number;
if (pos.overlayX == 'center') {
overlayStartX = -overlayRect.width / 2;
} else if (pos.overlayX === 'start') {
overlayStartX = this._isRtl() ? -overlayRect.width : 0;
} else {
overlayStartX = this._isRtl() ? 0 : -overlayRect.width;
}
let overlayStartY: number;
if (pos.overlayY == 'center') {
overlayStartY = -overlayRect.height / 2;
} else {
overlayStartY = pos.overlayY == 'top' ? 0 : -overlayRect.height;
}
// The (x, y) coordinates of the overlay.
return {
x: originPoint.x + overlayStartX,
y: originPoint.y + overlayStartY,
};
}
/** Gets how well an overlay at the given point will fit within the viewport. */
private _getOverlayFit(
point: Point,
overlay: ClientRect,
viewport: ClientRect,
position: ConnectedPosition,
): OverlayFit {
let { x, y } = point;
const offsetX = this._getOffset(position, 'x');
const offsetY = this._getOffset(position, 'y');
// Account for the offsets since they could push the overlay out of the viewport.
if (offsetX) {
x += offsetX;
}
if (offsetY) {
y += offsetY;
}
// How much the overlay would overflow at this position, on each side.
const leftOverflow = 0 - x;
const rightOverflow = x + overlay.width - viewport.width;
const topOverflow = 0 - y;
const bottomOverflow = y + overlay.height - viewport.height;
const insideHorizontalViewPortRect = y >= this._viewportBoundaries.top;
// Visible parts of the element on each axis.
const visibleWidth = this._subtractOverflows(
overlay.width,
leftOverflow,
rightOverflow,
);
let visibleHeight = this._subtractOverflows(
overlay.height,
topOverflow,
bottomOverflow,
);
if (!insideHorizontalViewPortRect) {
visibleHeight -= this._viewportBoundaries.top - y;
}
const visibleArea = visibleWidth * visibleHeight;
const isCompletelyWithinViewport =
overlay.width * overlay.height === visibleArea;
const fitsInViewportVertically = visibleHeight === overlay.height;
const fitsInViewportHorizontally = visibleWidth == overlay.width;
return {
visibleArea,
isCompletelyWithinViewport:
isCompletelyWithinViewport && insideHorizontalViewPortRect,
fitsInViewportVertically,
fitsInViewportHorizontally,
};
}
/**
* Whether the overlay can fit within the viewport when it may resize either its width or height.
* @param fit How well the overlay fits in the viewport at some position.
* @param point The (x, y) coordinates of the overlat at some position.
* @param viewport The geometry of the viewport.
*/
private _canFitWithFlexibleDimensions(
fit: OverlayFit,
point: Point,
viewport: ClientRect,
) {
if (this._hasFlexibleDimensions) {
const availableHeight = viewport.bottom - point.y;
const availableWidth = viewport.right - point.x;
const minHeight = this._overlayRef.getConfig().minHeight;
const minWidth = this._overlayRef.getConfig().minWidth;
const verticalFit =
fit.fitsInViewportVertically ||
(minHeight != null && minHeight <= availableHeight);
const horizontalFit =
fit.fitsInViewportHorizontally ||
(minWidth != null && minWidth <= availableWidth);
return verticalFit && horizontalFit;
}
return false;
}
/**
* Gets the point at which the overlay can be "pushed" on-screen. If the overlay is larger than
* the viewport, the top-left corner will be pushed on-screen (with overflow occuring on the
* right and bottom).
*
* @param start Starting point from which the overlay is pushed.
* @param overlay Dimensions of the overlay.
* @param scrollPosition Current viewport scroll position.
* @returns The point at which to position the overlay after pushing. This is effectively a new
* originPoint.
*/
private _pushOverlayOnScreen(
start: Point,
overlay: ClientRect,
scrollPosition: ViewportScrollPosition,
): Point {
// If the position is locked and we've pushed the overlay already, reuse the previous push
// amount, rather than pushing it again. If we were to continue pushing, the element would
// remain in the viewport, which goes against the expectations when position locking is enabled.
if (this._previousPushAmount && this._positionLocked) {
return {
x: start.x + this._previousPushAmount.x,
y: start.y + this._previousPushAmount.y,
};
}
const viewport = this._viewportRect;
// Determine how much the overlay goes outside the viewport on each
// side, which we'll use to decide which direction to push it.
const overflowRight = Math.max(start.x + overlay.width - viewport.right, 0);
const overflowBottom = Math.max(
start.y + overlay.height - viewport.bottom,
0,
);
const overflowTop = Math.max(
viewport.top - scrollPosition.top - start.y,
0,
);
const overflowLeft = Math.max(
viewport.left - scrollPosition.left - start.x,
0,
);
// Amount by which to push the overlay in each axis such that it remains on-screen.
let pushX = 0;
let pushY = 0;
// If the overlay fits completely within the bounds of the viewport, push it from whichever
// direction is goes off-screen. Otherwise, push the top-left corner such that its in the
// viewport and allow for the trailing end of the overlay to go out of bounds.
if (overlay.width <= viewport.width) {
pushX = overflowLeft || -overflowRight;
} else {
pushX =
start.x < this._viewportMargin
? viewport.left - scrollPosition.left - start.x
: 0;
}
if (overlay.height <= viewport.height) {
pushY = overflowTop || -overflowBottom;
} else {
pushY =
start.y < this._viewportMargin
? viewport.top - scrollPosition.top - start.y
: 0;
}
this._previousPushAmount = { x: pushX, y: pushY };
return {
x: start.x + pushX,
y: start.y + pushY,
};
}
/**
* Applies a computed position to the overlay and emits a position change.
* @param position The position preference
* @param originPoint The point on the origin element where the overlay is connected.
*/
private _applyPosition(position: ConnectedPosition, originPoint: Point) {
this._setTransformOrigin(position);
this._setOverlayElementStyles(originPoint, position);
this._setBoundingBoxStyles(originPoint, position);
if (position.panelClass) {
this._addPanelClasses(position.panelClass);
}
// Save the last connected position in case the position needs to be re-calculated.
this._lastPosition = position;
// Notify that the position has been changed along with its change properties.
// We only emit if we've got any subscriptions, because the scroll visibility
// calculcations can be somewhat expensive.
if (this._positionChanges.observers.length) {
const scrollableViewProperties = this._getScrollVisibility();
const changeEvent = new ConnectedOverlayPositionChange(
position,
scrollableViewProperties,
);
this._positionChanges.next(changeEvent);
}
this._isInitialRender = false;
}
/** Sets the transform origin based on the configured selector and the passed-in position. */
private _setTransformOrigin(position: ConnectedPosition) {
if (!this._transformOriginSelector) {
return;
}
const elements: NodeListOf<HTMLElement> = this._boundingBox!.querySelectorAll(
this._transformOriginSelector,
);
let xOrigin: 'left' | 'right' | 'center';
const yOrigin: 'top' | 'bottom' | 'center' = position.overlayY;
if (position.overlayX === 'center') {
xOrigin = 'center';
} else if (this._isRtl()) {
xOrigin = position.overlayX === 'start' ? 'right' : 'left';
} else {
xOrigin = position.overlayX === 'start' ? 'left' : 'right';
}
for (let i = 0; i < elements.length; i++) {
elements[i].style.transformOrigin = `${xOrigin} ${yOrigin}`;
}
}
/**
* Gets the position and size of the overlay's sizing container.
*
* This method does no measuring and applies no styles so that we can cheaply compute the
* bounds for all positions and choose the best fit based on these results.
*/
private _calculateBoundingBoxRect(
origin: Point,
position: ConnectedPosition,
): BoundingBoxRect {
const viewport = this._viewportRect;
const isRtl = this._isRtl();
let height: number, top: number, bottom: number;
if (position.overlayY === 'top') {
// Overlay is opening "downward" and thus is bound by the bottom viewport edge.
top = origin.y;
height = viewport.height - top + this._viewportMargin;
} else if (position.overlayY === 'bottom') {
// Overlay is opening "upward" and thus is bound by the top viewport edge. We need to add
// the viewport margin back in, because the viewport rect is narrowed down to remove the
// margin, whereas the `origin` position is calculated based on its `ClientRect`.
bottom = viewport.height - origin.y + this._viewportMargin * 2;
height = viewport.height - bottom + this._viewportMargin;
} else {
// If neither top nor bottom, it means that the overlay is vertically centered on the
// origin point. Note that we want the position relative to the viewport, rather than
// the page, which is why we don't use something like `viewport.bottom - origin.y` and
// `origin.y - viewport.top`.
const smallestDistanceToViewportEdge = Math.min(
viewport.bottom - origin.y + viewport.top,
origin.y,
);
const previousHeight = this._lastBoundingBoxSize.height;
height = smallestDistanceToViewportEdge * 2;
top = origin.y - smallestDistanceToViewportEdge;
if (
height > previousHeight &&
!this._isInitialRender &&
!this._growAfterOpen
) {
top = origin.y - previousHeight / 2;
}
}
// The overlay is opening 'right-ward' (the content flows to the right).
const isBoundedByRightViewportEdge =
(position.overlayX === 'start' && !isRtl) ||
(position.overlayX === 'end' && isRtl);
// The overlay is opening 'left-ward' (the content flows to the left).
const isBoundedByLeftViewportEdge =
(position.overlayX === 'end' && !isRtl) ||
(position.overlayX === 'start' && isRtl);
let width: number, left: number, right: number;
if (isBoundedByLeftViewportEdge) {
right = viewport.width - origin.x + this._viewportMargin;
width = origin.x - this._viewportMargin;
} else if (isBoundedByRightViewportEdge) {
left = origin.x;
width = viewport.right - origin.x;
} else {
// If neither start nor end, it means that the overlay is horizontally centered on the
// origin point. Note that we want the position relative to the viewport, rather than
// the page, which is why we don't use something like `viewport.right - origin.x` and
// `origin.x - viewport.left`.
const smallestDistanceToViewportEdge = Math.min(
viewport.right - origin.x + viewport.left,
origin.x,
);
const previousWidth = this._lastBoundingBoxSize.width;
width = smallestDistanceToViewportEdge * 2;
left = origin.x - smallestDistanceToViewportEdge;
if (
width > previousWidth &&
!this._isInitialRender &&
!this._growAfterOpen
) {
left = origin.x - previousWidth / 2;
}
}
return {
top: top!,
left: left!,
bottom: bottom!,
right: right!,
width,
height,
};
}
/**
* Sets the position and size of the overlay's sizing wrapper. The wrapper is positioned on the
* origin's connection point and stetches to the bounds of the viewport.
*
* @param origin The point on the origin element where the overlay is connected.
* @param position The position preference
*/
private _setBoundingBoxStyles(
origin: Point,
position: ConnectedPosition,
): void {
const boundingBoxRect = this._calculateBoundingBoxRect(origin, position);
// It's weird if the overlay *grows* while scrolling, so we take the last size into account
// when applying a new size.
if (!this._isInitialRender && !this._growAfterOpen) {
boundingBoxRect.height = Math.min(
boundingBoxRect.height,
this._lastBoundingBoxSize.height,
);
boundingBoxRect.width = Math.min(
boundingBoxRect.width,
this._lastBoundingBoxSize.width,
);
}
const styles = {
display: '',
} as CSSStyleDeclaration;
if (this._hasExactPosition()) {
styles.top = styles.left = '0';
styles.bottom = styles.right = '';
styles.width = styles.height = '100%';
} else {
const maxHeight = this._overlayRef.getConfig().maxHeight;
const maxWidth = this._overlayRef.getConfig().maxWidth;
styles.height = coerceCssPixelValue(boundingBoxRect.height);
styles.top = coerceCssPixelValue(boundingBoxRect.top);
styles.bottom = coerceCssPixelValue(boundingBoxRect.bottom);
styles.width = coerceCssPixelValue(boundingBoxRect.width);
styles.left = coerceCssPixelValue(boundingBoxRect.left);
styles.right = coerceCssPixelValue(boundingBoxRect.right);
// Push the pane content towards the proper direction.
if (position.overlayX === 'center') {
styles.alignItems = 'center';
} else {
styles.alignItems =
position.overlayX === 'end' ? 'flex-end' : 'flex-start';
}
if (position.overlayY === 'center') {
styles.justifyContent = 'center';
} else {
styles.justifyContent =
position.overlayY === 'bottom' ? 'flex-end' : 'flex-start';
}
if (maxHeight) {
styles.maxHeight = coerceCssPixelValue(maxHeight);
}
if (maxWidth) {
styles.maxWidth = coerceCssPixelValue(maxWidth);
}
}
this._lastBoundingBoxSize = boundingBoxRect;
this._isOutsideViewport = false;
extendStyles(this._boundingBox!.style, styles);