-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathct-menu.ts
More file actions
executable file
·282 lines (236 loc) · 7.39 KB
/
Copy pathct-menu.ts
File metadata and controls
executable file
·282 lines (236 loc) · 7.39 KB
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
import { Placement, autoUpdate, computePosition, flip, offset, shift } from "@floating-ui/dom";
import { html } from "lit";
import { CtLit, css, customElement, property, query } from "./ct-lit.js";
import {
closeFloatingMenuSurface,
createFloatingMenuPanel,
getFloatingMenuSurface,
isEventInsideMenuTree,
menuPanelStyles,
openFloatingMenuSurface,
setTransformOrigin,
shouldKeepMenuOpen,
staggerMenuItems,
type FloatingMenuOwner
} from "./ct-menu-shared.js";
type Align = "top" | "top-right" | "top-left" | "bottom" | "bottom-right" | "bottom-left";
/** Maps legacy `align` values to Floating UI placements. */
const ALIGN_TO_PLACEMENT: Record<Align, Placement> = {
top: "bottom",
"top-right": "bottom-end",
"top-left": "bottom-start",
bottom: "top",
"bottom-right": "top-end",
"bottom-left": "top-start"
};
/**
* # `ct-menu`
* @element ct-menu
* @description A dropdown menu component that displays a list of selectable items.
* The menu surface is portaled to `document.body` with `position: fixed` so it is
* not clipped by overflow/transform ancestors.
* @slot - Contains the menu items to be displayed when opened
* @slot trigger - The trigger element that opens/closes the dropdown menu
* @slot dropdown-trigger - (Deprecated) The trigger element that opens/closes the dropdown menu
* @fires open - Fired when the menu opens or closes. `detail` is the open state.
* @csspart menu - The dropdown menu container
* @cssproperty --color-surface - Background color of the menu (default: #fff)
* @cssproperty --color-on-surface - Text color of menu items (default: #474747)
* @cssproperty --border-radius - Border radius of the menu (default: 8px)
* @cssproperty --z-index-menu - Z-index of the floating menu (default: 1000)
*/
@customElement("ct-menu")
export class CtMenu extends CtLit implements FloatingMenuOwner {
@query("#items") $items!: HTMLSlotElement;
/**
* Preferred alignment of the menu relative to the trigger.
* Floating UI may flip/shift to keep the menu in view.
*/
@property({ type: String }) align: Align = "top-right";
/** Whether the menu is open */
@property({ type: Boolean, reflect: true }) opened = false;
/** Used by nested submenus to walk up the menu tree after portaling. */
_parentMenuOwner: FloatingMenuOwner | null = null;
private _panel: HTMLElement | null = null;
private _cleanupAutoUpdate?: () => void;
private _closeGeneration = 0;
static styles = css`
:host {
display: inline-block;
position: relative;
cursor: pointer;
color: inherit;
}
#items {
display: none;
}
`;
render() {
return html`
<slot name="dropdown-trigger" @click=${this._onTriggerClick}></slot>
<slot name="trigger" @click=${this._onTriggerClick}></slot>
<slot id="items"></slot>
`;
}
connectedCallback() {
super.connectedCallback();
document.addEventListener("click", this._handleOutsideClick);
document.addEventListener("keydown", this._handleKeydown);
}
disconnectedCallback() {
super.disconnectedCallback();
document.removeEventListener("click", this._handleOutsideClick);
document.removeEventListener("keydown", this._handleKeydown);
void this._teardownPanel({ immediate: true });
}
updated(changed: Map<PropertyKey, unknown>) {
if (changed.has("opened")) {
if (this.opened) {
this._openPanel();
} else {
this._teardownPanel();
this._closeNestedSubmenus();
}
this.setAttribute("aria-expanded", String(this.opened));
this.dispatchEvent(new CustomEvent("open", { detail: this.opened }));
}
if (changed.has("align") && this.opened) {
void this._updatePosition();
}
}
/** Opens the menu */
open(e?: Event) {
e?.stopPropagation();
this.opened = true;
}
/** Closes the menu */
close() {
this.opened = false;
}
/** Toggles the menu open state */
toggle(e?: Event) {
e?.stopPropagation();
this.opened = !this.opened;
}
private _onTriggerClick = (e: Event) => {
e.stopPropagation();
this.opened = !this.opened;
};
private _handleOutsideClick = (e: MouseEvent) => {
if (!this.opened) return;
if (!isEventInsideMenuTree(e.composedPath(), this, this._panel)) {
this.close();
}
};
private _handleKeydown = (e: KeyboardEvent) => {
if (e.key === "Escape" && this.opened) {
this.close();
}
};
private _getReference(): Element {
const triggers = this.shadowRoot?.querySelectorAll("slot[name='trigger'], slot[name='dropdown-trigger']");
if (triggers) {
for (let i = 0; i < triggers.length; i++) {
const [el] = (triggers[i] as HTMLSlotElement).assignedElements({ flatten: true });
if (el) return el;
}
}
return this;
}
private _getItemNodes(): Node[] {
return this.$items?.assignedNodes({ flatten: false }) ?? [];
}
private async _openPanel() {
this._closeGeneration++;
await this.updateComplete;
if (!this.opened) return;
if (!this._panel) {
this._panel = createFloatingMenuPanel(this, menuPanelStyles);
this._panel.addEventListener("click", this._onPanelClick);
}
const nodes = this._getItemNodes();
for (const node of nodes) {
this._panel.appendChild(node);
}
if (!this._panel.isConnected) {
document.body.appendChild(this._panel);
}
openFloatingMenuSurface(getFloatingMenuSurface(this._panel));
this._startPositioning();
staggerMenuItems(Array.from(this._panel.children));
}
private async _teardownPanel(options?: { immediate?: boolean }) {
this._stopPositioning();
if (!this._panel) return;
const panel = this._panel;
const generation = ++this._closeGeneration;
const surface = getFloatingMenuSurface(panel);
if (!options?.immediate) {
await closeFloatingMenuSurface(surface);
// Reopened (or another close started) while the animation was running.
if (generation !== this._closeGeneration || this.opened) return;
if (this._panel !== panel) return;
} else {
surface?.classList.remove("active", "closing");
}
while (panel.firstChild) {
this.appendChild(panel.firstChild);
}
panel.removeEventListener("click", this._onPanelClick);
panel.remove();
this._panel = null;
}
private _onPanelClick = (e: Event) => {
if (!shouldKeepMenuOpen(e.composedPath())) {
this.close();
}
};
private _closeNestedSubmenus() {
const roots: ParentNode[] = [this];
if (this._panel) roots.push(this._panel);
for (const root of roots) {
root.querySelectorAll("ct-submenu").forEach(el => {
(el as HTMLElement & { close(): void }).close();
});
}
}
private _startPositioning() {
const reference = this._getReference();
const floating = this._panel;
if (!floating) return;
this._stopPositioning();
this._cleanupAutoUpdate = autoUpdate(reference, floating, () => {
void this._updatePosition();
});
}
private _stopPositioning() {
this._cleanupAutoUpdate?.();
this._cleanupAutoUpdate = undefined;
}
private async _updatePosition() {
const floating = this._panel;
if (!floating || !this.opened) return;
const reference = this._getReference();
const placement = ALIGN_TO_PLACEMENT[this.align] ?? "bottom-end";
const {
x,
y,
placement: finalPlacement
} = await computePosition(reference, floating, {
placement,
strategy: "fixed",
middleware: [offset(4), flip({ padding: 8 }), shift({ padding: 8 })]
});
Object.assign(floating.style, {
left: `${x}px`,
top: `${y}px`
});
const surface = getFloatingMenuSurface(floating);
if (surface) setTransformOrigin(surface, finalPlacement);
}
}
declare global {
interface HTMLElementTagNameMap {
"ct-menu": CtMenu;
}
}