-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathaction-menu.tsx
executable file
·528 lines (411 loc) · 13.9 KB
/
action-menu.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
// @ts-strict-ignore
import { PropertyValues } from "lit";
import {
LitElement,
property,
createEvent,
Fragment,
h,
method,
state,
JsxNode,
} from "@arcgis/lumina";
import { getRoundRobinIndex } from "../../utils/array";
import { focusElement, toAriaBoolean } from "../../utils/dom";
import { FlipPlacement, LogicalPlacement, OverlayPositioning } from "../../utils/floating-ui";
import { guid } from "../../utils/guid";
import { isActivationKey } from "../../utils/key";
import { componentFocusable } from "../../utils/component";
import { Appearance, Scale } from "../interfaces";
import type { Action } from "../action/action";
import type { Tooltip } from "../tooltip/tooltip";
import { Popover } from "../popover/popover";
import { activeAttr, CSS, ICONS, SLOTS } from "./resources";
import { styles } from "./action-menu.scss";
declare global {
interface DeclareElements {
"calcite-action-menu": ActionMenu;
}
}
const SUPPORTED_MENU_NAV_KEYS = ["ArrowUp", "ArrowDown", "End", "Home"];
/**
* @slot - A slot for adding `calcite-action`s.
* @slot trigger - A slot for adding a `calcite-action` to trigger opening the menu.
* @slot tooltip - A slot for adding a tooltip for the menu.
*/
export class ActionMenu extends LitElement {
// #region Static Members
static override styles = styles;
// #endregion
// #region Private Properties
private guid = `calcite-action-menu-${guid()}`;
private actionElements: Action["el"][] = [];
private defaultMenuButtonEl: Action["el"];
private menuButtonClick = (): void => {
this.toggleOpen();
};
private menuButtonId = `${this.guid}-menu-button`;
private menuButtonKeyDown = (event: KeyboardEvent): void => {
const { key } = event;
const { actionElements, activeMenuItemIndex, open } = this;
if (!actionElements.length) {
return;
}
if (isActivationKey(key)) {
event.preventDefault();
if (!open) {
this.toggleOpen();
return;
}
const action = actionElements[activeMenuItemIndex];
if (action) {
action.click();
} else {
this.toggleOpen(false);
}
}
if (key === "Tab") {
this.open = false;
return;
}
if (key === "Escape") {
this.toggleOpen(false);
event.preventDefault();
return;
}
this.handleActionNavigation(event, key, actionElements);
};
private menuId = `${this.guid}-menu`;
private _open = false;
private popoverEl: Popover["el"];
private slottedMenuButtonEl: Action["el"];
private tooltipEl: Tooltip["el"];
private updateAction = (action: Action["el"], index: number): void => {
const { guid, activeMenuItemIndex } = this;
const id = `${guid}-action-${index}`;
action.tabIndex = -1;
action.setAttribute("role", "menuitem");
if (!action.id) {
action.id = id;
}
// data attribute is used to style the "activeMenuItemIndex" action using token focus styling.
action.toggleAttribute(activeAttr, index === activeMenuItemIndex);
};
// #endregion
// #region State Properties
@state() activeMenuItemIndex = -1;
@state() menuButtonEl: Action["el"];
// #endregion
// #region Public Properties
/** Specifies the appearance of the component. */
@property({ reflect: true }) appearance: Extract<"solid" | "transparent", Appearance> = "solid";
/** When `true`, the component is expanded. */
@property({ reflect: true }) expanded = false;
/** Specifies the component's fallback slotted content `placement` when it's initial or specified `placement` has insufficient space available. */
@property() flipPlacements: FlipPlacement[];
/**
* Specifies the text string for the component.
*
* @required
*/
@property() label: string;
/** When `true`, the component is open. */
@property({ reflect: true })
get open(): boolean {
return this._open;
}
set open(open: boolean) {
const oldOpen = this._open;
if (open !== oldOpen) {
this._open = open;
this.openHandler(open);
}
}
/**
* 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"` should be used to escape an overflowing parent container, or when the reference element's `position` CSS property is `"fixed"`.
*/
@property({ reflect: true }) overlayPositioning: OverlayPositioning = "absolute";
/** Determines where the component will be positioned relative to the `referenceElement`. */
@property({ reflect: true }) placement: LogicalPlacement = "auto";
/** Specifies the size of the component's trigger `calcite-action`. */
@property({ reflect: true }) scale: Scale = "m";
// #endregion
// #region Public Methods
/** Sets focus on the component. */
@method()
async setFocus(): Promise<void> {
await componentFocusable(this);
return focusElement(this.menuButtonEl);
}
// #endregion
// #region Events
/** Fires when the `open` property is toggled. */
calciteActionMenuOpen = createEvent({ cancelable: false });
// #endregion
// #region Lifecycle
override connectedCallback(): void {
this.connectMenuButtonEl();
}
override willUpdate(changes: PropertyValues<this>): void {
/* TODO: [MIGRATION] First time Lit calls willUpdate(), changes will include not just properties provided by the user, but also any default values your component set.
To account for this semantics change, the checks for (this.hasUpdated || value != defaultValue) was added in this method
Please refactor your code to reduce the need for this check.
Docs: https://qawebgis.esri.com/arcgis-components/?path=/docs/lumina-transition-from-stencil--docs#watching-for-property-changes */
if (changes.has("expanded") && (this.hasUpdated || this.expanded !== false)) {
this.expandedHandler();
}
if (
changes.has("activeMenuItemIndex") &&
(this.hasUpdated || this.activeMenuItemIndex !== -1)
) {
this.updateActions(this.actionElements);
}
}
override disconnectedCallback(): void {
this.disconnectMenuButtonEl();
}
// #endregion
// #region Private Methods
private expandedHandler(): void {
this.open = false;
this.setTooltipReferenceElement();
}
private openHandler(open: boolean): void {
if (this.menuButtonEl) {
this.menuButtonEl.active = open;
}
if (this.popoverEl) {
this.popoverEl.open = open;
}
this.activeMenuItemIndex = this.open ? 0 : -1;
this.calciteActionMenuOpen.emit();
this.setTooltipReferenceElement();
}
private connectMenuButtonEl(): void {
const { menuButtonId, menuId, open, label } = this;
const menuButtonEl = this.slottedMenuButtonEl || this.defaultMenuButtonEl;
if (this.menuButtonEl === menuButtonEl) {
return;
}
this.disconnectMenuButtonEl();
this.menuButtonEl = menuButtonEl;
this.setTooltipReferenceElement();
if (!menuButtonEl) {
return;
}
menuButtonEl.active = open;
menuButtonEl.setAttribute("aria-controls", menuId);
menuButtonEl.setAttribute("aria-expanded", toAriaBoolean(open));
menuButtonEl.setAttribute("aria-haspopup", "true");
if (!menuButtonEl.id) {
menuButtonEl.id = menuButtonId;
}
if (!menuButtonEl.label) {
menuButtonEl.label = label;
}
if (!menuButtonEl.text) {
menuButtonEl.text = label;
}
menuButtonEl.addEventListener(
"click",
this.menuButtonClick,
) /* TODO: [MIGRATION] If possible, refactor to use on* JSX prop or this.listen()/this.listenOn() utils - they clean up event listeners automatically, thus prevent memory leaks */;
menuButtonEl.addEventListener(
"keydown",
this.menuButtonKeyDown,
) /* TODO: [MIGRATION] If possible, refactor to use on* JSX prop or this.listen()/this.listenOn() utils - they clean up event listeners automatically, thus prevent memory leaks */;
}
private disconnectMenuButtonEl(): void {
const { menuButtonEl } = this;
if (!menuButtonEl) {
return;
}
menuButtonEl.removeEventListener(
"click",
this.menuButtonClick,
) /* TODO: [MIGRATION] If possible, refactor to use on* JSX prop or this.listen()/this.listenOn() utils - they clean up event listeners automatically, thus prevent memory leaks */;
menuButtonEl.removeEventListener(
"keydown",
this.menuButtonKeyDown,
) /* TODO: [MIGRATION] If possible, refactor to use on* JSX prop or this.listen()/this.listenOn() utils - they clean up event listeners automatically, thus prevent memory leaks */;
this.menuButtonEl = null;
}
private setMenuButtonEl(event: Event): void {
const actions = (event.target as HTMLSlotElement)
.assignedElements({
flatten: true,
})
.filter((el): el is Action["el"] => el?.matches("calcite-action"));
this.slottedMenuButtonEl = actions[0];
this.connectMenuButtonEl();
}
private setDefaultMenuButtonEl(el: Action["el"]): void {
this.defaultMenuButtonEl = el;
if (el) {
this.connectMenuButtonEl();
}
}
private setPopoverEl(el: Popover["el"]): void {
if (!el) {
return;
}
this.popoverEl = el;
el.open = this.open;
}
private handleCalciteActionClick(): void {
this.open = false;
this.setFocus();
}
private updateTooltip(event: Event): void {
const tooltips = (event.target as HTMLSlotElement)
.assignedElements({
flatten: true,
})
.filter((el): el is Tooltip["el"] => el?.matches("calcite-tooltip"));
this.tooltipEl = tooltips[0];
this.setTooltipReferenceElement();
}
private setTooltipReferenceElement(): void {
const { tooltipEl, expanded, menuButtonEl, open } = this;
if (tooltipEl) {
tooltipEl.referenceElement = !expanded && !open ? menuButtonEl : null;
}
}
private updateActions(actions: Action["el"][]): void {
actions?.forEach(this.updateAction);
}
private handleDefaultSlotChange(event: Event): void {
const actions = (event.target as HTMLSlotElement)
.assignedElements({
flatten: true,
})
.reduce<Action["el"][]>((previousValue, currentValue) => {
if (currentValue?.matches("calcite-action")) {
previousValue.push(currentValue as Action["el"]);
return previousValue;
}
if (currentValue?.matches("calcite-action-group")) {
return previousValue.concat(Array.from(currentValue.querySelectorAll("calcite-action")));
}
return previousValue;
}, []);
this.actionElements = actions.filter((action) => !action.disabled && !action.hidden);
}
private isValidKey(key: string, supportedKeys: string[]): boolean {
return !!supportedKeys.find((k) => k === key);
}
private handleActionNavigation(event: KeyboardEvent, key: string, actions: Action["el"][]): void {
if (!this.isValidKey(key, SUPPORTED_MENU_NAV_KEYS)) {
return;
}
event.preventDefault();
if (!this.open) {
this.toggleOpen();
if (key === "Home" || key === "ArrowDown") {
this.activeMenuItemIndex = 0;
}
if (key === "End" || key === "ArrowUp") {
this.activeMenuItemIndex = actions.length - 1;
}
return;
}
if (key === "Home") {
this.activeMenuItemIndex = 0;
}
if (key === "End") {
this.activeMenuItemIndex = actions.length - 1;
}
const currentIndex = this.activeMenuItemIndex;
if (key === "ArrowUp") {
this.activeMenuItemIndex = getRoundRobinIndex(Math.max(currentIndex - 1, -1), actions.length);
}
if (key === "ArrowDown") {
this.activeMenuItemIndex = getRoundRobinIndex(currentIndex + 1, actions.length);
}
}
private toggleOpen(value = !this.open): void {
this.open = value;
}
private handlePopoverOpen(): void {
this.open = true;
this.setFocus();
}
private handlePopoverClose(): void {
this.open = false;
}
// #endregion
// #region Rendering
private renderMenuButton(): JsxNode {
const { appearance, label, scale, expanded } = this;
const menuButtonSlot = (
<slot name={SLOTS.trigger} onSlotChange={this.setMenuButtonEl}>
<calcite-action
appearance={appearance}
class={CSS.defaultTrigger}
icon={ICONS.menu}
ref={this.setDefaultMenuButtonEl}
scale={scale}
text={label}
textEnabled={expanded}
/>
</slot>
);
return menuButtonSlot;
}
private renderMenuItems(): JsxNode {
const {
actionElements,
activeMenuItemIndex,
menuId,
menuButtonEl,
label,
placement,
overlayPositioning,
flipPlacements,
} = this;
const activeAction = actionElements[activeMenuItemIndex];
const activeDescendantId = activeAction?.id || null;
return (
<calcite-popover
autoClose={true}
flipPlacements={flipPlacements}
focusTrapDisabled={true}
label={label}
offsetDistance={0}
oncalcitePopoverClose={this.handlePopoverClose}
oncalcitePopoverOpen={this.handlePopoverOpen}
overlayPositioning={overlayPositioning}
placement={placement}
pointerDisabled={true}
ref={this.setPopoverEl}
referenceElement={menuButtonEl}
triggerDisabled={true}
>
<div
aria-activedescendant={activeDescendantId}
aria-labelledby={menuButtonEl?.id}
class={CSS.menu}
id={menuId}
onClick={this.handleCalciteActionClick}
role="menu"
tabIndex={-1}
>
<slot onSlotChange={this.handleDefaultSlotChange} />
</div>
</calcite-popover>
);
}
override render(): JsxNode {
return (
<>
{this.renderMenuButton()}
{this.renderMenuItems()}
<slot name={SLOTS.tooltip} onSlotChange={this.updateTooltip} />
</>
);
}
// #endregion
}