forked from andreasbm/weightless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
popover.ts
486 lines (420 loc) · 13.2 KB
/
popover.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
import { FocusTrap } from "@a11y/focus-trap";
import { customElement, html, property, query, TemplateResult } from "lit-element";
import "../backdrop";
import { Backdrop } from "../backdrop/backdrop";
import { IOverlayBehaviorBaseProperties, IOverlayBehaviorProperties, OverlayBehavior } from "../behavior/overlay/overlay-behavior";
import { AriaRole } from "../util/aria";
import { cssResult } from "../util/css";
import { queryParentRoots, renderAttributes, setProperty } from "../util/dom";
import { addClickAwayListener, addListener, EventListenerSubscription, removeListeners } from "../util/event";
import {
areStrategiesEqual,
computeAnchorPosition,
computeFallbackStrategy,
computeMaxDimensions,
computeTransformOrigin,
IAnchorPosition,
IPositionStrategy,
OriginX,
OriginY
} from "../util/position";
import { getOpacity, getScale } from "../util/style";
import styles from "./popover.scss";
/**
* Base properties of the popover.
*/
export interface IPopoverBaseProperties extends IPositionStrategy, IOverlayBehaviorBaseProperties {
closeOnClick: boolean;
role: AriaRole;
noFallback: boolean;
anchor?: Element | string;
}
/**
* Properties of the popover.
*/
export interface IPopoverProperties extends IPopoverBaseProperties, IOverlayBehaviorProperties {
anchorOpenEvents?: string[];
anchorCloseEvents?: string[];
}
/**
* Configuration for the popover.
*/
export interface IPopoverConfig extends Partial<IPopoverBaseProperties> {}
/**
* Default configuration for the popover.
*/
export const defaultPopoverConfig: IPopoverConfig = {
transformOriginX: OriginX.LEFT,
transformOriginY: OriginY.TOP,
anchorOriginX: OriginX.LEFT,
anchorOriginY: OriginY.TOP,
backdrop: false,
persistent: false,
duration: 300,
closeOnClick: false,
fixed: true
};
/**
* Contextual anchored elements.
* @slot - Default content.
* @cssprop --popover-z-index - z-index.
*/
@customElement("wl-popover")
export class Popover<R = unknown> extends OverlayBehavior<R, IPopoverConfig> implements IPopoverProperties {
static styles = [...OverlayBehavior.styles, cssResult(styles)];
/**
* Makes the popover close when it is clicked upon.
* @attr
*/
@property({ type: Boolean }) closeOnClick: boolean = false;
/**
* Whether a fallback strategy for the positioning should be used when there are no room for the popover.
* @attr
*/
@property({ type: Boolean }) noFallback: boolean = false;
/**
* X origin of the transform.
* @attr
*/
@property({ type: String, reflect: true }) transformOriginX: OriginX = OriginX.LEFT;
/**
* Y origin of the transform.
* @attr
*/
@property({ type: String, reflect: true }) transformOriginY: OriginY = OriginY.TOP;
/**
* X origin of the anchored point.
* @attr
*/
@property({ type: String, reflect: true }) anchorOriginX: OriginX = OriginX.LEFT;
/**
* Y origin of the anchored point.
* @attr
*/
@property({ type: String, reflect: true }) anchorOriginY: OriginY = OriginY.TOP;
/**
* Role of the popover.
* @attr
*/
@property({ type: String, reflect: true }) role: AriaRole = "menu";
/**
* Anchor element or query.
* @attr
*/
@property({ type: String }) anchor?: Element | string;
/**
* Events on the anchor that makes the popover open itself.
* @attr
*/
@property({ type: Array }) anchorOpenEvents?: string[];
/**
* Events on the anchor that makes the popover close itself.
* @attr
*/
@property({ type: Array }) anchorCloseEvents?: string[];
/**
* Content of the popover.
*/
@query("#content") protected $content!: FocusTrap;
/**
* Container element.
*/
@query("#container") protected $container!: HTMLElement;
/**
* Backdrop element.
*/
@query("#backdrop") protected $backdrop!: Backdrop;
/**
* Listeners that reacts when the user clicks outside the popover.
* Attached when when opened.
*/
private clickAwayListeners: EventListenerSubscription[] = [];
/**
* Listeners that opens the popover when event happens on the anchor.
*/
private anchorOpenEventListeners: EventListenerSubscription[] = [];
/**
* Listeners that closes the popover when event happens on the anchor.
*/
private anchorCloseEventListeners: EventListenerSubscription[] = [];
/**
* Position of the anchor.
*/
private anchorPosition?: IAnchorPosition;
/**
* Focus trap.
*/
get $focusTrap() {
return this.$content;
}
/**
* Tears down the component.
*/
disconnectedCallback() {
super.disconnectedCallback();
this.detachClickAwayListeners();
removeListeners(this.anchorOpenEventListeners);
removeListeners(this.anchorCloseEventListeners);
}
/**
* Reacts on the properties changed.
* @param props
*/
protected updated(props: Map<keyof IPopoverProperties, unknown>) {
super.updated(<Map<keyof IOverlayBehaviorProperties, unknown>>props);
// Attach auto open events to anchor
if (props.has("anchorOpenEvents") && this.anchorOpenEvents != null) {
this.attachEventListenersToAnchor(this.anchorOpenEventListeners, this.anchorOpenEvents, () => !this.open && this.show());
}
// Attach auto close events to anchor
if (props.has("anchorCloseEvents") && this.anchorCloseEvents != null) {
this.attachEventListenersToAnchor(this.anchorCloseEventListeners, this.anchorCloseEvents, () => this.open && this.hide());
}
}
/**
* Shows the popover at a specified screen position.
* @param position
* @param config
*/
showAtPosition(position: IAnchorPosition, config?: IPopoverConfig): Promise<R | null> {
this.anchorPosition = position;
return this.show(config);
}
/**
* The current position strategy of the popover.
* @returns {IPositionStrategy}
*/
protected getPositionStrategy(): IPositionStrategy {
return {
transformOriginX: this.transformOriginX,
transformOriginY: this.transformOriginY,
anchorOriginX: this.anchorOriginX,
anchorOriginY: this.anchorOriginY
};
}
/**
* Adds event listeners and focuses the first element after the popover has been shown.
*/
protected didShow() {
super.didShow();
// Focus the first element
this.$focusTrap.focusFirstElement();
// Attach click away listeners
this.attachClickAwayListeners();
}
/**
* Resets the component after the popover has been hidden.
*/
protected didHide(result?: R) {
super.didHide(result);
this.anchorPosition = undefined;
}
/**
* Attaches events listeners to the anchor.
* @param listeners
* @param events
* @param cb
*/
protected attachEventListenersToAnchor(listeners: EventListenerSubscription[], events: string[], cb: (e: Event) => void) {
// Detach the previous event listeners and attach the new ones.
removeListeners(listeners);
// Ensure that an anchor exists
const $anchor = this.getAnchor();
if ($anchor == null) {
return this.throwNoAnchorError();
}
// Add the listeners to the anchor
listeners.push(addListener($anchor, events, cb));
}
/**
* Throws an error that no anchor exists.
*/
protected throwNoAnchorError() {
throw new Error(`No anchor could be found for the popover. "${this.anchor}" provided as anchor.`);
}
/**
* Attaches the click away listeners.
*/
protected attachClickAwayListeners() {
this.clickAwayListeners.push(
addClickAwayListener([this.$container], this.clickAway.bind(this)),
addListener(this.$container, "click", this.onContainerClick.bind(this))
);
}
/**
* Detaches the click away listeners.
*/
protected detachClickAwayListeners() {
removeListeners(this.clickAwayListeners);
}
/**
* Animates the popover in.
*/
protected animateIn() {
// Callback for cleaning up the component and the animation
let ready = false;
const setup = () => {
if (ready) return;
ready = true;
this.didShow();
};
// Animate the backdrop in
const backdropAnimation = this.$backdrop.animate(
<PropertyIndexedKeyframes>{
opacity: [getOpacity(window.getComputedStyle(this.$backdrop)).toString(), `1`]
},
this.animationConfig
);
// Animate the popover in and take the intermediate stake into account
const contentComputedStyle = window.getComputedStyle(this.$content);
const contentScale = getScale(contentComputedStyle, this.$content.getBoundingClientRect());
const contentOpacity = getOpacity(contentComputedStyle);
const contentAnimation = this.$content.animate(
<PropertyIndexedKeyframes>{
transform: [`scale(${contentScale.x}, ${contentScale.y})`, `scale(1)`],
opacity: [`${contentOpacity > 0.5 ? contentOpacity : 0}`, 1]
},
this.animationConfig
);
contentAnimation.onfinish = setup;
backdropAnimation.onfinish = setup;
this.activeInAnimations.push(contentAnimation, backdropAnimation);
this.updatePosition();
}
/**
* Animates the popover out.
* @param result
*/
protected animateOut(result: R) {
// Callback for cleaning up the component and the animation
let cleaned = false;
const cleanup = () => {
if (cleaned) return;
cleaned = true;
this.resolve(result);
this.didHide(result);
};
// Animate the backdrop out
const backdropAnimation = this.$backdrop.animate(
<PropertyIndexedKeyframes>{
opacity: [getOpacity(window.getComputedStyle(this.$backdrop)).toString(), `0`]
},
this.animationConfig
);
// Animate the content out
const contentComputedStyle = window.getComputedStyle(this.$content);
const contentScale = getScale(contentComputedStyle, this.$content.getBoundingClientRect());
const contentOpacity = getOpacity(contentComputedStyle);
const contentAnimation = this.$content.animate(
<PropertyIndexedKeyframes>{
opacity: [contentOpacity.toString(), 0],
transform: [`scale(${contentScale.x}, ${contentScale.y})`, `scale(0)`]
},
this.animationConfig
);
backdropAnimation.onfinish = cleanup;
contentAnimation.onfinish = cleanup;
this.detachClickAwayListeners();
this.activeOutAnimations.push(backdropAnimation, contentAnimation);
}
/**
* Updates the position of the popover.
*/
protected updatePosition() {
super.updatePosition();
requestAnimationFrame(() => {
// Compute the anchor position and transform origin
const anchor = this.getAnchor();
let strategy = this.getPositionStrategy();
let isUsingFallbackStrategy = false;
let position!: IAnchorPosition;
let anchorRect: ClientRect | DOMRect | null = null;
// Always prioritize the anchor position set explicitly
if (this.anchorPosition != null) {
position = this.anchorPosition;
} else if (anchor != null) {
anchorRect = anchor!.getBoundingClientRect();
position = computeAnchorPosition(strategy, anchorRect);
} else {
return this.throwNoAnchorError();
}
// Compute a fallback strategy. Will not change if there are no need for a fallback.
if (!this.noFallback) {
const containerRect = this.$container.getBoundingClientRect();
const fallbackStrategy = computeFallbackStrategy(strategy, position, containerRect);
// Check whether the fallback strategy should be used
isUsingFallbackStrategy = areStrategiesEqual(strategy, fallbackStrategy);
if (isUsingFallbackStrategy) {
strategy = fallbackStrategy;
position = computeAnchorPosition(fallbackStrategy, anchorRect || position);
}
}
// Compute the transform of the popover
const transform = computeTransformOrigin(strategy);
this.$content.style.transformOrigin = `${strategy.transformOriginX} ${strategy.transformOriginY}`;
Object.assign(this.$container.style, {
top: `${position.top}px`,
left: `${position.left}px`,
transform: `translate(${transform.x}, ${transform.y})`
});
// Render the actual strategy as data attributes. This is used for the arrow in the wl-popover-card.
renderAttributes(this.$container, {
"data-fallback-strategy": isUsingFallbackStrategy,
"data-anchor-origin-x": strategy.anchorOriginX,
"data-anchor-origin-y": strategy.anchorOriginY,
"data-transform-origin-x": strategy.transformOriginX,
"data-transform-origin-y": strategy.transformOriginY
});
// Set the maximum height and width as CSS variables so the children can pick it up.
const { maxWidth, maxHeight } = computeMaxDimensions(strategy, position);
setProperty(`--popover-container-max-width`, `${maxWidth}px`, this.$container);
setProperty(`--popover-container-max-height`, `${maxHeight}px`, this.$container);
});
}
/**
* Returns the origin of the bounding box.
*/
private getAnchor(): Element | undefined {
let anchor = this.anchor;
// Check if the anchor is an ID.
if (typeof anchor === "string" || anchor instanceof String) {
const matches = queryParentRoots<Element>(this, <string>anchor);
anchor = matches.length > 0 ? matches[0] : undefined;
}
return anchor;
}
/**
* Handles the click event on the popover.
*/
private onContainerClick() {
if (this.open && this.closeOnClick) {
this.hide();
}
}
/**
* Renders the content.
*/
protected renderContent(): TemplateResult {
return html`
<slot></slot>
`;
}
/**
* Returns the template for the element.
*/
protected render(): TemplateResult {
return html`
<wl-backdrop id="backdrop" @click="${this.clickAway}"></wl-backdrop>
<div id="container" aria-expanded="${this.open.toString() as "true" | "false"}">
<focus-trap id="content" ?inactive="${!this.open || this.disableFocusTrap}">
${this.renderContent()}
</focus-trap>
</div>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
"wl-popover": Popover;
}
}