-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathoverflowManager.ts
More file actions
455 lines (384 loc) · 14.2 KB
/
Copy pathoverflowManager.ts
File metadata and controls
455 lines (384 loc) · 14.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
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
import { DATA_OVERFLOWING, DATA_OVERFLOW_GROUP } from './consts';
import { observeResize } from './createResizeObserver';
import { debounce } from './debounce';
import type { PriorityQueue } from './priorityQueue';
import { createPriorityQueue } from './priorityQueue';
import type {
OverflowGroupState,
OverflowItemEntry,
OverflowManager,
ObserveOptions,
OverflowDividerEntry,
OverflowEventPayload,
} from './types';
const DEFAULT_OPTIONS: Required<ObserveOptions> = {
overflowAxis: 'horizontal',
overflowDirection: 'end',
padding: 10,
minimumVisible: 0,
hasHiddenItems: false,
onUpdateItemVisibility: () => {
/* noop */
},
onUpdateOverflow: () => {
/* noop */
},
};
/**
* Creates an overflow manager instance for a single container.
*
* @internal
* @param initialOptions - Initial observe options. Missing values are filled with defaults.
* @returns overflow manager instance
*/
export function createOverflowManager(initialOptions: Partial<ObserveOptions> = {}): OverflowManager {
// calls to `offsetWidth or offsetHeight` can happen multiple times in an update
// Use a cache to avoid causing too many recalcs and avoid scripting time to meausure sizes
const sizeCache = new Map<HTMLElement, number>();
let container: HTMLElement | undefined;
let overflowMenu: HTMLElement | undefined;
// Set as true when resize observer is observing
let observing = false;
// If true, next update will dispatch to onUpdateOverflow even if queue top states don't change
// Initially true to force dispatch on first mount
let forceDispatch = true;
const options: Required<ObserveOptions> = { ...DEFAULT_OPTIONS, ...initialOptions };
const overflowItems: Record<string, OverflowItemEntry> = {};
const overflowDividers: Record<string, OverflowDividerEntry> = {};
const listeners = new Set<() => void>();
let disposeResizeObserver: () => void = () => {
/* noop */
};
let snapshot: OverflowEventPayload = {
visibleItems: [],
invisibleItems: [],
groupVisibility: {},
};
const takeSnapshot = (nextSnapshot: OverflowEventPayload) => {
snapshot = nextSnapshot;
options.onUpdateOverflow(snapshot);
listeners.forEach(listener => listener());
};
const getNextItem = (queueToDequeue: PriorityQueue<string>, queueToEnqueue: PriorityQueue<string>) => {
const nextItem = queueToDequeue.dequeue();
queueToEnqueue.enqueue(nextItem);
return overflowItems[nextItem];
};
const groupManager = createGroupManager();
function compareItems(lt: string | null, rt: string | null): number {
if (!lt || !rt) {
return 0;
}
const lte = overflowItems[lt];
const rte = overflowItems[rt];
// TODO this should not happen but there have been reports of one of these items being undefined
// Try to find a consistent repro for this
if (!lte || !rte) {
return lte ? 1 : -1;
}
// Pinned items have "infinite" priority - they should never be hidden
if (lte.pinned !== rte.pinned) {
return lte.pinned ? 1 : -1;
}
if (lte.priority !== rte.priority) {
return lte.priority > rte.priority ? 1 : -1;
}
// Node.DOCUMENT_POSITION_FOLLOWING = 4, Node.DOCUMENT_POSITION_PRECEDING = 2
const positionStatusBit = options.overflowDirection === 'end' ? 4 : 2;
// eslint-disable-next-line no-bitwise
return lte.element.compareDocumentPosition(rte.element) & positionStatusBit ? 1 : -1;
}
function getElementAxisSize(
horizontal: 'clientWidth' | 'offsetWidth',
vertical: 'clientHeight' | 'offsetHeight',
el: HTMLElement,
): number {
if (!sizeCache.has(el)) {
sizeCache.set(el, options.overflowAxis === 'horizontal' ? el[horizontal] : el[vertical]);
}
return sizeCache.get(el)!;
}
const getOffsetSize = getElementAxisSize.bind(null, 'offsetWidth', 'offsetHeight');
const getClientSize = getElementAxisSize.bind(null, 'clientWidth', 'clientHeight');
const invisibleItemQueue = createPriorityQueue<string>((a, b) => -1 * compareItems(a, b));
const visibleItemQueue = createPriorityQueue<string>(compareItems);
function occupiedSize(): number {
const totalItemSize = visibleItemQueue
.all()
.map(id => overflowItems[id].element)
.map(getOffsetSize)
.reduce((prev, current) => prev + current, 0);
const totalDividerSize = Object.entries(groupManager.groupVisibility()).reduce(
(acc, [id, state]) =>
acc + (state !== 'hidden' && overflowDividers[id] ? getOffsetSize(overflowDividers[id].element) : 0),
0,
);
const overflowMenuSize =
(invisibleItemQueue.size() > 0 || options.hasHiddenItems) && overflowMenu ? getOffsetSize(overflowMenu) : 0;
return totalItemSize + totalDividerSize + overflowMenuSize;
}
const showItem = () => {
const item = getNextItem(invisibleItemQueue, visibleItemQueue);
options.onUpdateItemVisibility({ item, visible: true });
if (item.groupId) {
groupManager.showItem(item.id, item.groupId);
if (groupManager.isSingleItemVisible(item.id, item.groupId)) {
overflowDividers[item.groupId]?.element.removeAttribute(DATA_OVERFLOWING);
}
}
};
const hideItem = () => {
const item = getNextItem(visibleItemQueue, invisibleItemQueue);
options.onUpdateItemVisibility({ item, visible: false });
if (item.groupId) {
if (groupManager.isSingleItemVisible(item.id, item.groupId)) {
overflowDividers[item.groupId]?.element.setAttribute(DATA_OVERFLOWING, '');
}
groupManager.hideItem(item.id, item.groupId);
}
};
const dispatchOverflowUpdate = () => {
const visibleItemIds = visibleItemQueue.all();
const invisibleItemIds = invisibleItemQueue.all();
const visibleItems = visibleItemIds.map(itemId => overflowItems[itemId]);
const invisibleItems = invisibleItemIds.map(itemId => overflowItems[itemId]);
takeSnapshot({
visibleItems,
invisibleItems,
groupVisibility: groupManager.groupVisibility(),
});
};
const getSnapshot: OverflowManager['getSnapshot'] = () => snapshot;
const processOverflowItems = (): boolean => {
if (!container) {
return false;
}
sizeCache.clear();
const availableSize = getClientSize(container) - options.padding;
// Snapshot of the visible/invisible state to compare for updates
const visibleTop = visibleItemQueue.peek();
const invisibleTop = invisibleItemQueue.peek();
while (compareItems(invisibleItemQueue.peek(), visibleItemQueue.peek()) > 0) {
hideItem(); // hide elements whose priority become smaller than the highest priority of the hidden one
}
// Run the show/hide step twice - the first step might not be correct if
// it was triggered by a new item being added - new items are always visible by default.
for (let i = 0; i < 2; i++) {
// Add items until available width is filled - can result in overflow
while (
(occupiedSize() < availableSize && invisibleItemQueue.size() > 0) ||
invisibleItemQueue.size() === 1 // attempt to show the last invisible item hoping it's size does not exceed overflow menu size
) {
showItem();
}
// Remove items until there's no more overflow
while (occupiedSize() > availableSize && visibleItemQueue.size() > options.minimumVisible) {
const nextItemId = visibleItemQueue.peek();
// Never hide pinned items - they should always remain visible
if (nextItemId && overflowItems[nextItemId]?.pinned) {
break;
}
hideItem();
}
}
// only update when the state of visible/invisible items has changed
return visibleItemQueue.peek() !== visibleTop || invisibleItemQueue.peek() !== invisibleTop;
};
const forceUpdate: OverflowManager['forceUpdate'] = () => {
if (processOverflowItems() || forceDispatch) {
forceDispatch = false;
dispatchOverflowUpdate();
}
};
const update: OverflowManager['update'] = debounce(forceUpdate);
const setOptions: OverflowManager['setOptions'] = nextOptions => {
if (options === nextOptions) {
return;
}
const shouldTriggerUpdate =
(nextOptions.overflowAxis && options.overflowAxis !== nextOptions.overflowAxis) ||
(nextOptions.overflowDirection && options.overflowDirection !== nextOptions.overflowDirection) ||
(nextOptions.padding && options.padding !== nextOptions.padding) ||
(nextOptions.minimumVisible && options.minimumVisible !== nextOptions.minimumVisible) ||
(nextOptions.hasHiddenItems && options.hasHiddenItems !== nextOptions.hasHiddenItems);
Object.assign(options, nextOptions);
if (shouldTriggerUpdate) {
forceDispatch = true;
update();
}
};
const observe: OverflowManager['observe'] = (observedContainer, userOptions) => {
if (userOptions) {
Object.assign(options, userOptions);
}
Object.values(overflowItems).forEach(item => {
if (!visibleItemQueue.contains(item.id) && !invisibleItemQueue.contains(item.id)) {
visibleItemQueue.enqueue(item.id);
}
});
container = observedContainer;
observing = true;
disposeResizeObserver = observeResize(container, entries => {
if (!entries[0] || !container) {
return;
}
update();
});
};
const disconnect: OverflowManager['disconnect'] = () => {
disposeResizeObserver();
disposeResizeObserver = () => {
/* noop */
};
// reset flags
container = undefined;
observing = false;
forceDispatch = true;
// clear all entries
Object.keys(overflowItems).forEach(itemId => removeItem(itemId));
Object.keys(overflowDividers).forEach(dividerId => removeDivider(dividerId));
removeOverflowMenu();
sizeCache.clear();
// notify subscribers that the manager is no longer tracking anything
takeSnapshot({
visibleItems: [],
invisibleItems: [],
groupVisibility: {},
});
};
const addItem: OverflowManager['addItem'] = items => {
if (overflowItems[items.id]) {
return;
}
overflowItems[items.id] = items;
// some options can affect priority which are only set on `observe`
if (observing) {
// Updates to elements might not change the queue tops
// i.e. new element is enqueued but the top of the queue stays the same
// force a dispatch on the next batched update
forceDispatch = true;
visibleItemQueue.enqueue(items.id);
update();
}
if (items.groupId) {
groupManager.addItem(items.id, items.groupId);
items.element.setAttribute(DATA_OVERFLOW_GROUP, items.groupId);
}
};
const addOverflowMenu: OverflowManager['addOverflowMenu'] = el => {
overflowMenu = el;
};
const addDivider: OverflowManager['addDivider'] = divider => {
if (!divider.groupId || overflowDividers[divider.groupId]) {
return;
}
divider.element.setAttribute(DATA_OVERFLOW_GROUP, divider.groupId);
overflowDividers[divider.groupId] = divider;
};
const removeOverflowMenu: OverflowManager['removeOverflowMenu'] = () => {
overflowMenu = undefined;
};
const removeDivider: OverflowManager['removeDivider'] = groupId => {
if (!overflowDividers[groupId]) {
return;
}
const divider = overflowDividers[groupId];
if (divider.groupId) {
delete overflowDividers[groupId];
divider.element.removeAttribute(DATA_OVERFLOW_GROUP);
}
};
const removeItem: OverflowManager['removeItem'] = itemId => {
if (!overflowItems[itemId]) {
return;
}
if (observing) {
// We might be removing an item in an overflow which would not affect the tops,
// but we need to update anyway to update the overflow menu state
forceDispatch = true;
}
const item = overflowItems[itemId];
visibleItemQueue.remove(itemId);
invisibleItemQueue.remove(itemId);
if (item.groupId) {
groupManager.removeItem(item.id, item.groupId);
item.element.removeAttribute(DATA_OVERFLOW_GROUP);
}
sizeCache.delete(item.element);
delete overflowItems[itemId];
if (observing) {
update();
}
};
const subscribe: OverflowManager['subscribe'] = listener => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
};
return {
addItem,
disconnect,
forceUpdate,
observe,
removeItem,
update,
addOverflowMenu,
removeOverflowMenu,
addDivider,
removeDivider,
setOptions,
getSnapshot,
subscribe,
};
}
const createGroupManager = () => {
const groupVisibility: Record<string, OverflowGroupState> = {};
const groups: Record<string, { visibleItemIds: Set<string>; invisibleItemIds: Set<string> }> = {};
function updateGroupVisibility(groupId: string) {
const group = groups[groupId];
if (group.invisibleItemIds.size && group.visibleItemIds.size) {
groupVisibility[groupId] = 'overflow';
} else if (group.visibleItemIds.size === 0) {
groupVisibility[groupId] = 'hidden';
} else {
groupVisibility[groupId] = 'visible';
}
}
function isGroupVisible(groupId: string) {
return groupVisibility[groupId] === 'visible' || groupVisibility[groupId] === 'overflow';
}
return {
groupVisibility: () => groupVisibility,
isSingleItemVisible(itemId: string, groupId: string) {
return (
isGroupVisible(groupId) &&
groups[groupId].visibleItemIds.has(itemId) &&
groups[groupId].visibleItemIds.size === 1
);
},
addItem(itemId: string, groupId: string) {
groups[groupId] ??= {
visibleItemIds: new Set<string>(),
invisibleItemIds: new Set<string>(),
};
groups[groupId].visibleItemIds.add(itemId);
updateGroupVisibility(groupId);
},
removeItem(itemId: string, groupId: string) {
groups[groupId].invisibleItemIds.delete(itemId);
groups[groupId].visibleItemIds.delete(itemId);
updateGroupVisibility(groupId);
},
showItem(itemId: string, groupId: string) {
groups[groupId].invisibleItemIds.delete(itemId);
groups[groupId].visibleItemIds.add(itemId);
updateGroupVisibility(groupId);
},
hideItem(itemId: string, groupId: string) {
groups[groupId].invisibleItemIds.add(itemId);
groups[groupId].visibleItemIds.delete(itemId);
updateGroupVisibility(groupId);
},
};
};