-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathresponsive-container.element.ts
More file actions
330 lines (275 loc) · 10.2 KB
/
responsive-container.element.ts
File metadata and controls
330 lines (275 loc) · 10.2 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
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
import type { UUIButtonElement } from '../button/button.js';
import type { UUIPopoverContainerElement } from '../popover-container/popover-container.js';
import { css, html, LitElement } from 'lit';
import { property, query, queryAssignedElements } from 'lit/decorators.js';
import { repeat } from 'lit/directives/repeat.js';
import '../button/button.js';
import '../popover-container/popover-container.js';
import '../symbol-more/symbol-more.js';
/**
* A responsive container that collapses overflowing children into a dropdown.
*
* @element uui-responsive-container
* @slot - Default slot for child elements (buttons, etc.)
* @cssprop --uui-responsive-container-gap - Gap between items (default: 8px)
*/
export class UUIResponsiveContainerElement extends LitElement {
// These help us find elements inside the component
@query('#more-button')
private readonly _moreButtonElement!: UUIButtonElement;
@query('#popover-container')
private readonly _popoverContainerElement!: UUIPopoverContainerElement;
@query('#main')
private readonly _mainElement!: HTMLElement;
/**
* Controls which side items collapse from.
* - "end": Items collapse from the right, more button appears on right (default)
* - "start": Items collapse from the left, more button appears on left
* @attr collapse
* @default "end"
*/
@property({ type: String, reflect: true })
collapse: 'start' | 'end' = 'end';
// This gets all elements put inside the slot
@queryAssignedElements({ flatten: true })
private readonly _slottedNodes?: HTMLElement[];
// These store the component's internal state
#childElements: HTMLElement[] = []; // All child elements
#hiddenElements: HTMLElement[] = []; // Elements in the dropdown
#hiddenElementsMap: Map<HTMLElement, HTMLElement> = new Map();
#visibilityBreakpoints: number[] = []; // Width thresholds for each item
// ResizeObserver watches for size changes
#resizeObserver = new ResizeObserver(this.#onResize.bind(this));
#childResizeObservers: ResizeObserver[] = [];
#breakPointCalculationInProgress = false;
#isConnected = false;
connectedCallback() {
super.connectedCallback();
this.#isConnected = true;
this.#initialize();
}
disconnectedCallback() {
super.disconnectedCallback();
this.#isConnected = false;
this.#resizeObserver.disconnect();
this.#cleanup();
}
async #initialize() {
await this.updateComplete;
if (!this.#isConnected) return;
this.#resizeObserver.observe(this._mainElement);
requestAnimationFrame(() => {
if (!this.#isConnected) return;
this.#onSlotChange();
});
}
// This runs when the container size changes
#onResize(entries: ResizeObserverEntry[]) {
if (!this.#isConnected) return;
const newWidth = entries[0].contentBoxSize[0].inlineSize;
this.#updateCollapsibleItems(newWidth);
}
// This runs when children are added/removed
#onSlotChange() {
if (!this.#isConnected) return;
this.#cleanup();
this.#childElements = this._slottedNodes ? [...this._slottedNodes] : [];
this.#childElements.forEach(el => {
const observer = new ResizeObserver(
this.#calculateBreakPoints.bind(this),
);
observer.observe(el);
this.#childResizeObservers.push(observer);
});
this.#calculateBreakPoints();
}
#cleanup() {
this.#childResizeObservers.forEach(observer => observer.disconnect());
this.#childResizeObservers = [];
this.#visibilityBreakpoints = [];
// Clean up hidden elements
this.#hiddenElements.forEach(el => {
el.removeEventListener('click', this.#onItemClicked);
});
this.#hiddenElements = [];
this.#hiddenElementsMap.clear();
}
// Calculate at what widths items should hide
async #calculateBreakPoints() {
if (!this.#isConnected) return;
if (this.#breakPointCalculationInProgress) return;
this.#breakPointCalculationInProgress = true;
await this.updateComplete;
// Get the gap from CSS or use default
const gapCSSVar = Number.parseFloat(
getComputedStyle(this).getPropertyValue('--uui-responsive-container-gap'),
);
const gap = Number.isNaN(gapCSSVar) ? 8 : gapCSSVar;
let totalWidth = 0;
// Calculate cumulative width for each item
for (let i = 0; i < this.#childElements.length; i++) {
this.#childElements[i].style.display = '';
totalWidth += this.#childElements[i].offsetWidth;
this.#visibilityBreakpoints[i] = totalWidth;
totalWidth += gap;
}
// Set the container width
const tolerance = 2;
this._mainElement.style.width = totalWidth - gap + tolerance + 'px';
this.#updateCollapsibleItems(this._mainElement.offsetWidth);
this.#breakPointCalculationInProgress = false;
}
// The main logic that shows/hides items
#updateCollapsibleItems(containerWidth: number) {
const moreButtonWidth = this._moreButtonElement?.offsetWidth || 40;
const availableWidth = containerWidth - moreButtonWidth;
// Clear previous hidden items
this.#hiddenElements.forEach(el => {
el.removeEventListener('click', this.#onItemClicked);
});
this.#hiddenElements = [];
this.#hiddenElementsMap.clear();
const len = this.#visibilityBreakpoints.length;
if (this.collapse === 'end') {
// Collapse from the END (right side) - current behavior
for (let i = 0; i < len; i++) {
const breakpoint = this.#visibilityBreakpoints[i];
const element = this.#childElements[i];
// Last item: use full width (no more button needed if all fit)
const widthToCheck = i === len - 1 ? containerWidth : availableWidth;
if (breakpoint <= widthToCheck) {
element.style.display = '';
} else {
element.style.display = 'none';
const clone = element.cloneNode(true) as HTMLElement;
clone.style.display = '';
clone.addEventListener('click', this.#onItemClicked);
// Link clone ↔ original (bidirectional)
this.#hiddenElementsMap.set(clone, element);
this.#hiddenElementsMap.set(element, clone);
this.#hiddenElements.push(clone);
}
}
} else {
// Collapse from the START (left side)
// Calculate total width of all items
const totalWidth = this.#visibilityBreakpoints[len - 1] || 0;
for (let i = 0; i < len; i++) {
const element = this.#childElements[i];
// Width from this item to the end
const widthFromEnd =
totalWidth - (i > 0 ? this.#visibilityBreakpoints[i - 1] : 0);
// First visible item: use full width (no more button needed if all fit)
const isFirstPotentiallyVisible =
i === 0 || this.#childElements[i - 1].style.display === 'none';
const widthToCheck =
isFirstPotentiallyVisible && this.#hiddenElements.length === 0
? containerWidth
: availableWidth;
if (widthFromEnd <= widthToCheck) {
element.style.display = '';
} else {
element.style.display = 'none';
const clone = element.cloneNode(true) as HTMLElement;
clone.style.display = '';
clone.addEventListener('click', this.#onItemClicked);
// Link clone ↔ original (bidirectional)
this.#hiddenElementsMap.set(clone, element);
this.#hiddenElementsMap.set(element, clone);
this.#hiddenElements.push(clone);
}
}
}
// Show/hide the "more" button
if (this.#hiddenElements.length === 0) {
this._moreButtonElement.style.display = 'none';
this._popoverContainerElement?.hidePopover();
} else {
this._moreButtonElement.style.display = '';
}
this.requestUpdate();
}
#onItemClicked = (e: MouseEvent) => {
const clickedElement = e.currentTarget as HTMLElement;
// Find the original element linked to this clone
const originalElement = this.#hiddenElementsMap.get(clickedElement);
if (originalElement) {
// Close the dropdown
this._popoverContainerElement?.hidePopover();
// Trigger click on the ORIGINAL element so its event handlers fire
originalElement.click();
}
};
render() {
const moreButton = html`
<uui-button
popovertarget="popover-container"
style="display: none"
id="more-button"
label="More"
compact>
<slot name="trigger-content">
<uui-symbol-more></uui-symbol-more>
</slot>
</uui-button>
`;
return html`
<div id="main">
${this.collapse === 'start' ? moreButton : ''}
<div id="items-container">
<slot @slotchange=${this.#onSlotChange}></slot>
</div>
${this.collapse === 'end' ? moreButton : ''}
</div>
<uui-popover-container
id="popover-container"
popover
placement=${this.collapse === 'start' ? 'bottom-start' : 'bottom-end'}>
<div id="dropdown-container">
${repeat(this.#hiddenElements, el => html`${el}`)}
</div>
</uui-popover-container>
`;
}
static override readonly styles = [
css`
:host {
display: flex;
min-width: 0;
}
#main {
display: flex;
overflow: hidden;
align-items: center;
}
#items-container {
display: flex;
gap: var(--uui-responsive-container-gap, var(--uui-size-3));
overflow: hidden;
align-items: center;
}
#more-button {
--uui-button-background-color: transparent;
--uui-button-background-color-hover: var(--uui-color-surface-alt);
flex-shrink: 0;
}
:host([collapse='end']) #more-button,
:host(:not([collapse])) #more-button {
margin-left: var(--uui-responsive-container-gap, var(--uui-size-3));
}
:host([collapse='start']) #more-button {
margin-right: var(--uui-responsive-container-gap, var(--uui-size-3));
}
#dropdown-container {
display: flex;
flex-direction: column;
background-color: var(--uui-color-surface);
border-radius: var(--uui-border-radius);
box-shadow: var(--uui-shadow-depth-3);
overflow: hidden;
padding: var(--uui-size-space-2);
gap: var(--uui-size-space-1);
}
`,
];
}