-
Notifications
You must be signed in to change notification settings - Fork 892
/
surfacePositionController.ts
505 lines (456 loc) · 17.3 KB
/
surfacePositionController.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
/**
* @license
* Copyright 2023 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {ReactiveController, ReactiveControllerHost} from 'lit';
import {StyleInfo} from 'lit/directives/style-map.js';
/**
* An enum of supported Menu corners
*/
// tslint:disable-next-line:enforce-name-casing We are mimicking enum style
export const Corner = {
END_START: 'end-start',
END_END: 'end-end',
START_START: 'start-start',
START_END: 'start-end',
} as const;
/**
* A corner of a box in the standard logical property style of <block>_<inline>
*/
export type Corner = typeof Corner[keyof typeof Corner];
/**
* An interface that provides a method to customize the rect from which to
* calculate the anchor positioning. Useful for when you want a surface to
* anchor to an element in your shadow DOM rather than the host element.
*/
export interface SurfacePositionTarget extends HTMLElement {
getSurfacePositionClientRect?: () => DOMRect;
}
/**
* The configurable options for the surface position controller.
*/
export interface SurfacePositionControllerProperties {
/**
* The corner of the anchor to align the surface's position.
*/
anchorCorner: Corner;
/**
* The corner of the surface to align to the given anchor corner.
*/
surfaceCorner: Corner;
/**
* The HTMLElement reference of the surface to be positioned.
*/
surfaceEl: SurfacePositionTarget|null;
/**
* The HTMLElement reference of the anchor to align to.
*/
anchorEl: SurfacePositionTarget|null;
/**
* Whether the positioning algorithim should calculate relative to the parent
* of the anchor element (absolute) or relative to the window (fixed).
*
* Examples for `position = 'fixed'`:
*
* - If there is no `position:relative` in the given parent tree and the
* surface is `position:absolute`
* - If the surface is `position:fixed`
* - If the surface is in the "top layer"
* - The anchor and the surface do not share a common `position:relative`
* ancestor
*/
positioning: 'absolute'|'fixed';
/**
* Whether or not the surface should be "open" and visible
*/
isOpen: boolean;
/**
* The number of pixels in which to offset from the inline axis relative to
* logical property.
*
* Positive is right in LTR and left in RTL.
*/
xOffset: number;
/**
* The number of pixes in which to offset the block axis.
*
* Positive is down and negative is up.
*/
yOffset: number;
/**
* The strategy to follow when repositioning the menu to stay inside the
* viewport. "move" will simply move the surface to stay in the viewport.
* "resize" will attempt to resize the surface.
*
* Both strategies will still attempt to flip the anchor and surface corners.
*/
repositionStrategy: 'move'|'resize';
/**
* A function to call after the surface has been positioned.
*/
onOpen: () => void;
/**
* A function to call before the surface should be closed. (A good time to
* perform animations while the surface is still visible)
*/
beforeClose: () => Promise<void>;
/**
* A function to call after the surface has been closed.
*/
onClose: () => void;
}
/**
* Given a surface, an anchor, corners, and some options, this surface will
* calculate the position of a surface to align the two given corners and keep
* the surface inside the window viewport. It also provides a StyleInfo map that
* can be applied to the surface to handle visiblility and position.
*/
export class SurfacePositionController implements ReactiveController {
// The current styles to apply to the surface.
private surfaceStylesInternal: StyleInfo = {
'display': 'none',
};
// Previous values stored for change detection. Open change detection is
// calculated separately so initialize it here.
private lastValues: SurfacePositionControllerProperties = {isOpen: false} as
SurfacePositionControllerProperties;
/**
* @param host The host to connect the controller to.
* @param getProperties A function that returns the properties for the
* controller.
*/
constructor(
private readonly host: ReactiveControllerHost,
private readonly getProperties: () => SurfacePositionControllerProperties,
) {
this.host.addController(this);
}
/**
* The StyleInfo map to apply to the surface via Lit's stylemap
*/
get surfaceStyles() {
return this.surfaceStylesInternal;
}
/**
* Calculates the surface's new position required so that the surface's
* `surfaceCorner` aligns to the anchor's `anchorCorner` while keeping the
* surface inside the window viewport. This positioning also respects RTL by
* checking `getComputedStyle()` on the surface element.
*/
async position() {
const {
surfaceEl,
anchorEl,
anchorCorner: anchorCornerRaw,
surfaceCorner: surfaceCornerRaw,
positioning,
xOffset,
yOffset,
repositionStrategy,
} = this.getProperties();
const anchorCorner = anchorCornerRaw.toLowerCase().trim();
const surfaceCorner = surfaceCornerRaw.toLowerCase().trim();
if (!surfaceEl || !anchorEl) {
return;
}
// Paint the surface transparently so that we can get the position and the
// rect info of the surface.
this.surfaceStylesInternal = {
'display': 'block',
'opacity': '0',
};
// Wait for it to be visible.
this.host.requestUpdate();
await this.host.updateComplete;
const surfaceRect = surfaceEl.getSurfacePositionClientRect ?
surfaceEl.getSurfacePositionClientRect() :
surfaceEl.getBoundingClientRect();
const anchorRect = anchorEl.getSurfacePositionClientRect ?
anchorEl.getSurfacePositionClientRect() :
anchorEl.getBoundingClientRect();
const [surfaceBlock, surfaceInline] =
surfaceCorner.split('-') as Array<'start'|'end'>;
const [anchorBlock, anchorInline] =
anchorCorner.split('-') as Array<'start'|'end'>;
// LTR depends on the direction of the SURFACE not the anchor.
const isLTR =
getComputedStyle(surfaceEl as HTMLElement).direction === 'ltr';
/*
* A diagram that helps describe some of the variables used in the following
* calculations.
*
* ┌───── inline/blockTopLayerOffset
* │ │
* │ ┌─▼───┐ Window
* │ ┌┼─────┴────────────────────────┐
* │ ││ │
* └──► ││ ┌──inline/blockAnchorOffset │
* ││ │ │ │
* └┤ │ ┌──▼───┐ │
* │ │ ┌┼──────┤ │
* │ └─►│Anchor│ │
* │ └┴──────┘ │
* │ │
* │ ┌────────────────────────┼────┐
* │ │ Surface │ │
* │ │ │ │
* │ │ │ │
* │ │ │ │
* │ │ │ │
* │ │ │ │
* └─────┼────────────────────────┘ ├┐
* │ inline/blockOOBCorrection ││
* │ │ ││
* │ ├──►││
* │ │ ││
* └────────────────────────┐▼───┼┘
* └────┘
*/
// Calculate the block positioning properties
let {blockInset, blockOutOfBoundsCorrection, surfaceBlockProperty} =
this.calculateBlock({
surfaceRect,
anchorRect,
anchorBlock,
surfaceBlock,
yOffset,
positioning
});
// If the surface should be out of bounds in the block direction, flip the
// surface and anchor corner block values and recalculate
if (blockOutOfBoundsCorrection) {
const flippedSurfaceBlock = surfaceBlock === 'start' ? 'end' : 'start';
const flippedAnchorBlock = anchorBlock === 'start' ? 'end' : 'start';
const flippedBlock = this.calculateBlock({
surfaceRect,
anchorRect,
anchorBlock: flippedAnchorBlock,
surfaceBlock: flippedSurfaceBlock,
yOffset,
positioning
});
// In the case that the flipped verion would require less out of bounds
// correcting, use the flipped corner block values
if (blockOutOfBoundsCorrection >
flippedBlock.blockOutOfBoundsCorrection) {
blockInset = flippedBlock.blockInset;
blockOutOfBoundsCorrection = flippedBlock.blockOutOfBoundsCorrection;
surfaceBlockProperty = flippedBlock.surfaceBlockProperty;
}
}
// Calculate the inline positioning properties
let {inlineInset, inlineOutOfBoundsCorrection, surfaceInlineProperty} =
this.calculateInline({
surfaceRect,
anchorRect,
anchorInline,
surfaceInline,
xOffset,
positioning,
isLTR,
});
// If the surface should be out of bounds in the inline direction, flip the
// surface and anchor corner inline values and recalculate
if (inlineOutOfBoundsCorrection) {
const flippedSurfaceInline = surfaceInline === 'start' ? 'end' : 'start';
const flippedAnchorInline = anchorInline === 'start' ? 'end' : 'start';
const flippedInline = this.calculateInline({
surfaceRect,
anchorRect,
anchorInline: flippedAnchorInline,
surfaceInline: flippedSurfaceInline,
xOffset,
positioning,
isLTR,
});
// In the case that the flipped verion would require less out of bounds
// correcting, use the flipped corner inline values
if (Math.abs(inlineOutOfBoundsCorrection) >
Math.abs(flippedInline.inlineOutOfBoundsCorrection)) {
inlineInset = flippedInline.inlineInset;
inlineOutOfBoundsCorrection = flippedInline.inlineOutOfBoundsCorrection;
surfaceInlineProperty = flippedInline.surfaceInlineProperty;
}
}
// If we are simply repositioning the surface back inside the viewport,
// subtract the out of bounds correction values from the positioning.
if (repositionStrategy === 'move') {
blockInset = blockInset - blockOutOfBoundsCorrection;
inlineInset = inlineInset - inlineOutOfBoundsCorrection;
}
this.surfaceStylesInternal = {
'display': 'block',
'opacity': '1',
[surfaceBlockProperty]: `${blockInset}px`,
[surfaceInlineProperty]: `${inlineInset}px`,
};
// In the case that we are resizing the surface to stay inside the viewport
// we need to set height and width on the surface.
if (repositionStrategy === 'resize') {
// Add a height property to the styles if there is block height correction
if (blockOutOfBoundsCorrection) {
this.surfaceStylesInternal['height'] =
`${surfaceRect.height - blockOutOfBoundsCorrection}px`;
}
// Add a width property to the styles if there is block height correction
if (inlineOutOfBoundsCorrection) {
this.surfaceStylesInternal['width'] =
`${surfaceRect.width - inlineOutOfBoundsCorrection}px`;
}
}
this.host.requestUpdate();
}
/**
* Calculates the css property, the inset, and the out of bounds correction
* for the surface in the block direction.
*/
private calculateBlock(config: {
surfaceRect: DOMRect,
anchorRect: DOMRect,
anchorBlock: 'start'|'end',
surfaceBlock: 'start'|'end',
yOffset: number,
positioning: 'absolute'|'fixed',
}) {
const {
surfaceRect,
anchorRect,
anchorBlock,
surfaceBlock,
yOffset,
positioning,
} = config;
// We use number booleans to multiply values rather than `if` / ternary
// statements because it _heavily_ cuts down on nesting and readability
const relativeToWindow = positioning === 'fixed' ? 1 : 0;
const isSurfaceBlockStart = surfaceBlock === 'start' ? 1 : 0;
const isSurfaceBlockEnd = surfaceBlock === 'end' ? 1 : 0;
const isOneBlockEnd = anchorBlock !== surfaceBlock ? 1 : 0;
// Whether or not to apply the height of the anchor
const blockAnchorOffset = isOneBlockEnd * anchorRect.height + yOffset;
// The absolute block position of the anchor relative to window
const blockTopLayerOffset = isSurfaceBlockStart * anchorRect.top +
isSurfaceBlockEnd * (window.innerHeight - anchorRect.bottom);
// If the surface's block would be out of bounds of the window, move it back
// in
const blockOutOfBoundsCorrection = Math.abs(Math.min(
0,
window.innerHeight - blockTopLayerOffset - blockAnchorOffset -
surfaceRect.height));
// The block logical value of the surface
const blockInset =
relativeToWindow * blockTopLayerOffset + blockAnchorOffset;
const surfaceBlockProperty =
surfaceBlock === 'start' ? 'inset-block-start' : 'inset-block-end';
return {blockInset, blockOutOfBoundsCorrection, surfaceBlockProperty};
}
/**
* Calculates the css property, the inset, and the out of bounds correction
* for the surface in the inline direction.
*/
private calculateInline(config: {
isLTR: boolean,
surfaceInline: 'start'|'end',
anchorInline: 'start'|'end',
anchorRect: DOMRect,
surfaceRect: DOMRect,
xOffset: number,
positioning: 'absolute'|'fixed',
}) {
const {
isLTR: isLTRBool,
surfaceInline,
anchorInline,
anchorRect,
surfaceRect,
xOffset,
positioning,
} = config;
// We use number booleans to multiply values rather than `if` / ternary
// statements because it _heavily_ cuts down on nesting and readability
const relativeToWindow = positioning === 'fixed' ? 1 : 0;
const isLTR = isLTRBool ? 1 : 0;
const isRTL = isLTRBool ? 0 : 1;
const isSurfaceInlineStart = surfaceInline === 'start' ? 1 : 0;
const isSurfaceInlineEnd = surfaceInline === 'end' ? 1 : 0;
const isOneInlineEnd = anchorInline !== surfaceInline ? 1 : 0;
// Whether or not to apply the width of the anchor
const inlineAnchorOffset = isOneInlineEnd * anchorRect.width + xOffset;
// The inline position of the anchor relative to window in LTR
const inlineTopLayerOffsetLTR = isSurfaceInlineStart * anchorRect.left +
isSurfaceInlineEnd * (window.innerWidth - anchorRect.right);
// The inline position of the anchor relative to window in RTL
const inlineTopLayerOffsetRTL =
isSurfaceInlineStart * (window.innerWidth - anchorRect.right) +
isSurfaceInlineEnd * anchorRect.left;
// The inline position of the anchor relative to window
const inlineTopLayerOffset =
isLTR * inlineTopLayerOffsetLTR + isRTL * inlineTopLayerOffsetRTL;
// If the surface's inline would be out of bounds of the window, move it
// back in
const inlineOutOfBoundsCorrection = Math.abs(Math.min(
0,
window.innerWidth - inlineTopLayerOffset - inlineAnchorOffset -
surfaceRect.width));
// The inline logical value of the surface
const inlineInset =
relativeToWindow * inlineTopLayerOffset + inlineAnchorOffset;
const surfaceInlineProperty =
surfaceInline === 'start' ? 'inset-inline-start' : 'inset-inline-end';
return {
inlineInset,
inlineOutOfBoundsCorrection,
surfaceInlineProperty,
};
}
hostUpdate() {
this.onUpdate();
}
hostUpdated() {
this.onUpdate();
}
/**
* Checks whether the properties passed into the controller have changed since
* the last positioning. If so, it will reposition if the surface is open or
* close it if the surface should close.
*/
private async onUpdate() {
const props = this.getProperties();
let hasChanged = false;
for (const [key, value] of Object.entries(props)) {
// tslint:disable-next-line
hasChanged = hasChanged || (value !== (this.lastValues as any)[key]);
if (hasChanged) break;
}
const openChanged = this.lastValues.isOpen !== props.isOpen;
const hasAnchor = !!props.anchorEl;
const hasSurface = !!props.surfaceEl;
if (hasChanged && hasAnchor && hasSurface) {
// Only update isOpen, because if it's closed, we do not want to waste
// time on a useless reposition calculation. So save the other "dirty"
// values until next time it opens.
this.lastValues.isOpen = props.isOpen;
if (props.isOpen) {
// We are going to do a reposition, so save the prop values for future
// dirty checking.
this.lastValues = props;
await this.position();
props.onOpen();
} else if (openChanged) {
await props.beforeClose();
this.close();
props.onClose();
}
}
}
/**
* Hides the surface.
*/
private close() {
this.surfaceStylesInternal = {
'display': 'none',
};
this.host.requestUpdate();
}
}