-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathpopover.tsx
605 lines (508 loc) · 15.9 KB
/
popover.tsx
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
import {
Component,
Element,
Event,
EventEmitter,
forceUpdate,
h,
Host,
Method,
Prop,
State,
VNode,
Watch,
} from "@stencil/core";
import {
connectFloatingUI,
defaultOffsetDistance,
disconnectFloatingUI,
filterValidFlipPlacements,
FlipPlacement,
FloatingCSS,
FloatingLayout,
FloatingUIComponent,
LogicalPlacement,
OverlayPositioning,
ReferenceElement,
reposition,
} from "../../utils/floating-ui";
import {
activateFocusTrap,
connectFocusTrap,
deactivateFocusTrap,
FocusTrap,
FocusTrapComponent,
updateFocusTrapElements,
} from "../../utils/focusTrapComponent";
import { focusFirstTabbable, queryElementRoots, toAriaBoolean } from "../../utils/dom";
import { guid } from "../../utils/guid";
import { onToggleOpenCloseComponent, OpenCloseComponent } from "../../utils/openCloseComponent";
import { Heading, HeadingLevel } from "../functional/Heading";
import { Scale } from "../interfaces";
import { connectLocalized, disconnectLocalized, LocalizedComponent } from "../../utils/locale";
import {
connectMessages,
disconnectMessages,
setUpMessages,
T9nComponent,
updateMessages,
} from "../../utils/t9n";
import {
componentFocusable,
LoadableComponent,
setComponentLoaded,
setUpLoadableComponent,
} from "../../utils/loadable";
import { createObserver } from "../../utils/observers";
import { FloatingArrow } from "../functional/FloatingArrow";
import { getIconScale } from "../../utils/component";
import PopoverManager from "./PopoverManager";
import { PopoverMessages } from "./assets/popover/t9n";
import { ARIA_CONTROLS, ARIA_EXPANDED, CSS, defaultPopoverPlacement } from "./resources";
const manager = new PopoverManager();
/**
* @slot - A slot for adding custom content.
*/
@Component({
tag: "calcite-popover",
styleUrl: "popover.scss",
shadow: true,
assetsDirs: ["assets"],
})
export class Popover
implements
FloatingUIComponent,
OpenCloseComponent,
FocusTrapComponent,
LoadableComponent,
LocalizedComponent,
T9nComponent
{
// --------------------------------------------------------------------------
//
// Properties
//
// --------------------------------------------------------------------------
/**
* When `true`, clicking outside of the component automatically closes open `calcite-popover`s.
*/
@Prop({ reflect: true }) autoClose = false;
/** When `true`, displays a close button within the component. */
@Prop({ reflect: true }) closable = false;
/**
* When `true`, prevents flipping the component's placement when overlapping its `referenceElement`.
*/
@Prop({ reflect: true }) flipDisabled = false;
/**
* When `true`, prevents focus trapping.
*/
@Prop({ reflect: true }) focusTrapDisabled = false;
@Watch("focusTrapDisabled")
handleFocusTrapDisabled(focusTrapDisabled: boolean): void {
if (!this.open) {
return;
}
focusTrapDisabled ? deactivateFocusTrap(this) : activateFocusTrap(this);
}
/**
* When `true`, removes the caret pointer.
*/
@Prop({ reflect: true }) pointerDisabled = false;
/**
* Specifies the component's fallback `placement` when it's initial or specified `placement` has insufficient space available.
*/
@Prop() flipPlacements: FlipPlacement[];
@Watch("flipPlacements")
flipPlacementsHandler(): void {
this.setFilteredPlacements();
this.reposition(true);
}
/**
* The component header text.
*/
@Prop() heading: string;
/**
* Specifies the heading level of the component's `heading` for proper document structure, without affecting visual styling.
*/
@Prop({ reflect: true }) headingLevel: HeadingLevel;
/** Accessible name for the component. */
@Prop() label!: string;
/**
* Use this property to override individual strings used by the component.
*/
// eslint-disable-next-line @stencil-community/strict-mutable -- updated by t9n module
@Prop({ mutable: true }) messageOverrides: Partial<PopoverMessages>;
@Watch("messageOverrides")
onMessagesChange(): void {
/* wired up by t9n util */
}
/**
* Made into a prop for testing purposes only
*
* @internal
*/
// eslint-disable-next-line @stencil-community/strict-mutable -- updated by t9n module
@Prop({ mutable: true }) messages: PopoverMessages;
/**
* Offsets the position of the popover away from the `referenceElement`.
*
* @default 6
*/
@Prop({ reflect: true }) offsetDistance = defaultOffsetDistance;
@Watch("offsetDistance")
offsetDistanceOffsetHandler(): void {
this.reposition(true);
}
/**
* Offsets the position of the component along the `referenceElement`.
*/
@Prop({ reflect: true }) offsetSkidding = 0;
@Watch("offsetSkidding")
offsetSkiddingHandler(): void {
this.reposition(true);
}
/**
* When `true`, displays and positions the component.
*/
@Prop({ reflect: true, mutable: true }) open = false;
@Watch("open")
openHandler(): void {
onToggleOpenCloseComponent(this);
this.reposition(true);
this.setExpandedAttr();
}
/**
* Determines the type of positioning to use for the overlaid content.
*
* Using `"absolute"` will work for most cases. The component will be positioned inside of overflowing parent containers and will affect the container's layout.
*
* `"fixed"` value should be used to escape an overflowing parent container, or when the reference element's `position` CSS property is `"fixed"`.
*
*/
@Prop({ reflect: true }) overlayPositioning: OverlayPositioning = "absolute";
@Watch("overlayPositioning")
overlayPositioningHandler(): void {
this.reposition(true);
}
/**
* Determines where the component will be positioned relative to the `referenceElement`.
*/
@Prop({ reflect: true }) placement: LogicalPlacement = defaultPopoverPlacement;
@Watch("placement")
placementHandler(): void {
this.reposition(true);
}
/**
* The `referenceElement` used to position the component according to its `placement` value. Setting to an `HTMLElement` is preferred so the component does not need to query the DOM. However, a string `id` of the reference element can also be used.
*/
@Prop() referenceElement!: ReferenceElement | string;
@Watch("referenceElement")
referenceElementHandler(): void {
this.setUpReferenceElement();
this.reposition(true);
}
/** Specifies the size of the component. */
@Prop({ reflect: true }) scale: Scale = "m";
/**
* When `true`, disables automatically toggling the component when its `referenceElement` has been triggered.
*
* This property can be set to `true` to manage when the component is open.
*/
@Prop({ reflect: true }) triggerDisabled = false;
// --------------------------------------------------------------------------
//
// Private Properties
//
// --------------------------------------------------------------------------
@Element() el: HTMLCalcitePopoverElement;
mutationObserver: MutationObserver = createObserver("mutation", () =>
this.updateFocusTrapElements(),
);
filteredFlipPlacements: FlipPlacement[];
@State() effectiveLocale = "";
@State() floatingLayout: FloatingLayout = "vertical";
@Watch("effectiveLocale")
effectiveLocaleChange(): void {
updateMessages(this, this.effectiveLocale);
}
@State() effectiveReferenceElement: ReferenceElement;
@State() defaultMessages: PopoverMessages;
arrowEl: SVGSVGElement;
closeButtonEl: HTMLCalciteActionElement;
guid = `calcite-popover-${guid()}`;
openTransitionProp = "opacity";
transitionEl: HTMLDivElement;
hasLoaded = false;
focusTrap: FocusTrap;
// --------------------------------------------------------------------------
//
// Lifecycle
//
// --------------------------------------------------------------------------
connectedCallback(): void {
this.setFilteredPlacements();
connectLocalized(this);
connectMessages(this);
connectFocusTrap(this);
// we set up the ref element in the next frame to ensure PopoverManager
// event handlers are invoked after connect (mainly for `components` output target)
requestAnimationFrame(() => this.setUpReferenceElement(this.hasLoaded));
}
async componentWillLoad(): Promise<void> {
await setUpMessages(this);
setUpLoadableComponent(this);
}
componentDidLoad(): void {
setComponentLoaded(this);
if (this.referenceElement && !this.effectiveReferenceElement) {
this.setUpReferenceElement();
}
if (this.open) {
onToggleOpenCloseComponent(this);
}
this.hasLoaded = true;
}
disconnectedCallback(): void {
this.removeReferences();
disconnectLocalized(this);
disconnectMessages(this);
disconnectFloatingUI(this, this.effectiveReferenceElement, this.el);
deactivateFocusTrap(this);
}
//--------------------------------------------------------------------------
//
// Events
//
//--------------------------------------------------------------------------
/** Fires when the component is requested to be closed and before the closing transition begins. */
@Event({ cancelable: false }) calcitePopoverBeforeClose: EventEmitter<void>;
/** Fires when the component is closed and animation is complete. */
@Event({ cancelable: false }) calcitePopoverClose: EventEmitter<void>;
/** Fires when the component is added to the DOM but not rendered, and before the opening transition begins. */
@Event({ cancelable: false }) calcitePopoverBeforeOpen: EventEmitter<void>;
/** Fires when the component is open and animation is complete. */
@Event({ cancelable: false }) calcitePopoverOpen: EventEmitter<void>;
// --------------------------------------------------------------------------
//
// Public Methods
//
// --------------------------------------------------------------------------
/**
* Updates the position of the component.
*
* @param delayed
*/
@Method()
async reposition(delayed = false): Promise<void> {
const {
el,
effectiveReferenceElement,
placement,
overlayPositioning,
flipDisabled,
filteredFlipPlacements,
offsetDistance,
offsetSkidding,
arrowEl,
} = this;
return reposition(
this,
{
floatingEl: el,
referenceEl: effectiveReferenceElement,
overlayPositioning,
placement,
flipDisabled,
flipPlacements: filteredFlipPlacements,
offsetDistance,
offsetSkidding,
arrowEl,
type: "popover",
},
delayed,
);
}
/**
* Sets focus on the component's first focusable element.
*/
@Method()
async setFocus(): Promise<void> {
await componentFocusable(this);
forceUpdate(this.el);
focusFirstTabbable(this.el);
}
/**
* Updates the element(s) that are used within the focus-trap of the component.
*/
@Method()
async updateFocusTrapElements(): Promise<void> {
updateFocusTrapElements(this);
}
// --------------------------------------------------------------------------
//
// Private Methods
//
// --------------------------------------------------------------------------
private setTransitionEl = (el: HTMLDivElement): void => {
this.transitionEl = el;
};
setFilteredPlacements = (): void => {
const { el, flipPlacements } = this;
this.filteredFlipPlacements = flipPlacements
? filterValidFlipPlacements(flipPlacements, el)
: null;
};
setUpReferenceElement = (warn = true): void => {
this.removeReferences();
this.effectiveReferenceElement = this.getReferenceElement();
connectFloatingUI(this, this.effectiveReferenceElement, this.el);
const { el, referenceElement, effectiveReferenceElement } = this;
if (warn && referenceElement && !effectiveReferenceElement) {
console.warn(`${el.tagName}: reference-element id "${referenceElement}" was not found.`, {
el,
});
}
this.addReferences();
};
getId = (): string => {
return this.el.id || this.guid;
};
setExpandedAttr = (): void => {
const { effectiveReferenceElement, open } = this;
if (!effectiveReferenceElement) {
return;
}
if ("setAttribute" in effectiveReferenceElement) {
effectiveReferenceElement.setAttribute(ARIA_EXPANDED, toAriaBoolean(open));
}
};
addReferences = (): void => {
const { effectiveReferenceElement } = this;
if (!effectiveReferenceElement) {
return;
}
const id = this.getId();
if ("setAttribute" in effectiveReferenceElement) {
effectiveReferenceElement.setAttribute(ARIA_CONTROLS, id);
}
manager.registerElement(effectiveReferenceElement, this.el);
this.setExpandedAttr();
};
removeReferences = (): void => {
const { effectiveReferenceElement } = this;
if (!effectiveReferenceElement) {
return;
}
if ("removeAttribute" in effectiveReferenceElement) {
effectiveReferenceElement.removeAttribute(ARIA_CONTROLS);
effectiveReferenceElement.removeAttribute(ARIA_EXPANDED);
}
manager.unregisterElement(effectiveReferenceElement);
};
getReferenceElement(): ReferenceElement {
const { referenceElement, el } = this;
return (
(typeof referenceElement === "string"
? queryElementRoots(el, { id: referenceElement })
: referenceElement) || null
);
}
hide = (): void => {
this.open = false;
};
onBeforeOpen(): void {
this.calcitePopoverBeforeOpen.emit();
}
onOpen(): void {
this.calcitePopoverOpen.emit();
activateFocusTrap(this);
}
onBeforeClose(): void {
this.calcitePopoverBeforeClose.emit();
}
onClose(): void {
this.calcitePopoverClose.emit();
deactivateFocusTrap(this);
}
storeArrowEl = (el: SVGSVGElement): void => {
this.arrowEl = el;
this.reposition(true);
};
// --------------------------------------------------------------------------
//
// Render Methods
//
// --------------------------------------------------------------------------
renderCloseButton(): VNode {
const { messages, closable } = this;
return closable ? (
<div class={CSS.closeButtonContainer} key={CSS.closeButtonContainer}>
<calcite-action
appearance="transparent"
class={CSS.closeButton}
onClick={this.hide}
ref={(closeButtonEl) => (this.closeButtonEl = closeButtonEl)}
scale={this.scale}
text={messages.close}
>
<calcite-icon icon="x" scale={getIconScale(this.scale)} />
</calcite-action>
</div>
) : null;
}
renderHeader(): VNode {
const { heading, headingLevel } = this;
const headingNode = heading ? (
<Heading class={CSS.heading} level={headingLevel}>
{heading}
</Heading>
) : null;
return headingNode ? (
<div class={CSS.header} key={CSS.header}>
{headingNode}
{this.renderCloseButton()}
</div>
) : null;
}
render(): VNode {
const { effectiveReferenceElement, heading, label, open, pointerDisabled, floatingLayout } =
this;
const displayed = effectiveReferenceElement && open;
const hidden = !displayed;
const arrowNode = !pointerDisabled ? (
<FloatingArrow floatingLayout={floatingLayout} key="floating-arrow" ref={this.storeArrowEl} />
) : null;
return (
<Host
aria-hidden={toAriaBoolean(hidden)}
aria-label={label}
aria-live="polite"
calcite-hydrated-hidden={hidden}
id={this.getId()}
role="dialog"
>
<div
class={{
[FloatingCSS.animation]: true,
[FloatingCSS.animationActive]: displayed,
}}
ref={this.setTransitionEl}
>
{arrowNode}
<div
class={{
[CSS.hasHeader]: !!heading,
[CSS.container]: true,
}}
>
{this.renderHeader()}
<div class={CSS.content}>
<slot />
</div>
{!heading ? this.renderCloseButton() : null}
</div>
</div>
</Host>
);
}
}