-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathFloatingMenu.svelte
More file actions
863 lines (731 loc) · 34.6 KB
/
FloatingMenu.svelte
File metadata and controls
863 lines (731 loc) · 34.6 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
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
<script lang="ts" context="module">
export type MenuType = "Popover" | "Tooltip" | "Dropdown" | "Dialog" | "Cursor";
/// Prevents the escape key from closing the parent floating menu of the given element.
/// This works by momentarily setting the `data-escape-does-not-close` attribute on the parent floating menu element.
/// After checking for the Escape key, it checks (in one `setTimeout`) for the attribute and ignores the key if it's present.
/// Then after two calls of `setTimeout`, we can safely remove the attribute here.
export function preventEscapeClosingParentFloatingMenu(element: HTMLElement) {
const floatingMenuParent = element.closest("[data-floating-menu-content]") || undefined;
if (floatingMenuParent instanceof HTMLElement) {
floatingMenuParent.setAttribute("data-escape-does-not-close", "");
setTimeout(() => {
setTimeout(() => {
floatingMenuParent.removeAttribute("data-escape-does-not-close");
}, 0);
}, 0);
}
}
</script>
<script lang="ts">
import { onMount, afterUpdate, createEventDispatcher, tick } from "svelte";
import type { MenuDirection } from "@graphite/messages";
import { browserVersion } from "@graphite/utility-functions/platform";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
const BUTTON_LEFT = 0;
const POINTER_STRAY_DISTANCE = 100;
const dispatch = createEventDispatcher<{ open: boolean; naturalWidth: number }>();
let className = "";
export { className as class };
export let classes: Record<string, boolean> = {};
let styleName = "";
export { styleName as style };
export let styles: Record<string, string | number | undefined> = {};
export let open: boolean;
export let type: MenuType;
export let direction: MenuDirection = "Bottom";
export let windowEdgeMargin = 6;
export let scrollableY = false;
export let minWidth = 0;
export let escapeCloses = true;
export let strayCloses = true;
let tail: HTMLDivElement | undefined;
let self: HTMLDivElement | undefined;
let floatingMenuContainer: HTMLDivElement | undefined;
let floatingMenuContent: LayoutCol | undefined;
// The resize observer is attached to the floating menu container, which is the zero-height div of the width of the parent element's floating menu spawner.
// Since CSS doesn't let us make the floating menu (with `position: fixed`) have a 100% width of this container, we need to use JS to observe its size and
// tell the floating menu content to use it as a min-width so the floating menu is at least the width of the parent element's floating menu spawner.
// This is the opposite concern of the natural width measurement system, which gets the natural width of the floating menu content in order for the
// spawner widget to optionally set its min-size to the floating menu's natural width.
let containerResizeObserver = new ResizeObserver((entries: ResizeObserverEntry[]) => {
resizeObserverCallback(entries);
});
let wasOpen = open;
let measuringOngoing = false;
let measuringOngoingGuard = false;
let minWidthParentWidth = 0;
let pointerStillDown = false;
let floatingMenuBounds = new DOMRect();
let floatingMenuContentBounds = new DOMRect();
$: watchOpenChange(open);
$: minWidthStyleValue = measuringOngoing ? "0" : `${Math.max(minWidth, minWidthParentWidth)}px`;
$: displayTail = open && type === "Popover";
$: displayContainer = open || measuringOngoing;
$: extraClasses = Object.entries(classes)
.flatMap(([className, stateName]) => (stateName ? [className] : []))
.join(" ");
$: extraStyles = Object.entries(styles)
.flatMap((styleAndValue) => (styleAndValue[1] !== undefined ? [`${styleAndValue[0]}: ${styleAndValue[1]};`] : []))
.join(" ");
// Generic function to get constraint bounds for positioning
// Returns the bounds of the scrollable parent if one exists, otherwise returns window bounds
function getConstraintBounds(element: HTMLElement | undefined): DOMRect {
const scrollableParent = element?.closest("[data-scrollable-x], [data-scrollable-y]");
if (scrollableParent) {
return scrollableParent.getBoundingClientRect();
}
return document.documentElement.getBoundingClientRect();
}
// Called only when `open` is changed from outside this component
async function watchOpenChange(isOpen: boolean) {
const scrollableParent = self?.closest("[data-scrollable-x], [data-scrollable-y]");
const isInScrollableContainer = Boolean(scrollableParent);
// Mitigate a Safari rendering bug which clips the floating menu extending beyond a scrollable container.
// The bug is possibly related to <https://bugs.webkit.org/show_bug.cgi?id=160953>, but in our case it happens when `overflow` of a parent is `auto` rather than `hidden`.
// Only apply if NOT in scrollable container
if (browserVersion().toLowerCase().includes("safari") && !isInScrollableContainer) {
const scrollable = self?.closest("[data-scrollable-x], [data-scrollable-y]");
if (scrollable instanceof HTMLElement) {
// The issue exists when the container is set to `overflow: auto` but fine when `overflow: hidden`. So this workaround temporarily sets
// the scrollable container to `overflow: hidden`, thus removing the scrollbars and ability to scroll until the floating menu is closed.
scrollable.style.overflow = isOpen ? "hidden" : "";
}
}
// Switching from closed to open
if (isOpen && !wasOpen) {
// TODO: Close any other floating menus that may already be open, which can happen using tab navigation and Enter/Space Bar to open
// Close floating menu if pointer strays far enough away
window.addEventListener("pointermove", pointerMoveHandler);
// Close floating menu if esc is pressed
window.addEventListener("keydown", keyDownHandler);
// Close floating menu if pointer is outside (but within stray distance)
window.addEventListener("pointerdown", pointerDownHandler);
// Cancel the subsequent click event to prevent the floating menu from reopening if the floating menu's button is the click event target
window.addEventListener("pointerup", pointerUpHandler);
await tick();
// Add scroll listener for menus in scrollable containers
if (isInScrollableContainer && scrollableParent) {
const scrollHandler = () => {
// Get constraint bounds from scrollable parent
const constraintBounds = scrollableParent.getBoundingClientRect();
const buttonBounds = self?.getBoundingClientRect();
// Close menu if button is scrolled out of view
if (buttonBounds) {
const isOffScreen =
buttonBounds.right < constraintBounds.left ||
buttonBounds.left > constraintBounds.right ||
buttonBounds.bottom < constraintBounds.top ||
buttonBounds.top > constraintBounds.bottom;
if (isOffScreen) {
dispatch("open", false);
return;
}
}
// Update position
positionAndStyleFloatingMenu();
};
scrollableParent.addEventListener("scroll", scrollHandler);
}
// Floating menu min-width resize observer
// Start a new observation of the now-open floating menu
if (floatingMenuContainer) {
containerResizeObserver.disconnect();
containerResizeObserver.observe(floatingMenuContainer);
}
}
// Switching from open to closed
if (!isOpen && wasOpen) {
// Clean up observation of the now-closed floating menu
containerResizeObserver.disconnect();
window.removeEventListener("pointermove", pointerMoveHandler);
window.removeEventListener("keydown", keyDownHandler);
window.removeEventListener("pointerdown", pointerDownHandler);
// The `pointerup` event is removed in `pointerMoveHandler()` and `pointerDownHandler()`
// Clean up scroll listener
if (isInScrollableContainer && scrollableParent) {
scrollableParent.removeEventListener("scroll", positionAndStyleFloatingMenu);
}
}
// Now that we're done reading the old state, update it to the current state for next time
wasOpen = isOpen;
}
onMount(() => {
// Measure the content and round up its width and height to the nearest even integer.
// This solves antialiasing issues when the content isn't cleanly divisible by 2 and gets translated by (-50%, -50%) causing all its content to be blurry.
const floatingMenuContentDiv = floatingMenuContent?.div?.();
if (type === "Dialog" && floatingMenuContentDiv) {
const resizeObserver = new ResizeObserver((entries) => {
entries.forEach((entry) => {
const existingWidth = Number(floatingMenuContentDiv.style.getPropertyValue("--even-integer-subpixel-expansion-x"));
const existingHeight = Number(floatingMenuContentDiv.style.getPropertyValue("--even-integer-subpixel-expansion-y"));
let { width, height } = entry.contentRect;
width -= existingWidth;
height -= existingHeight;
let targetWidth = Math.ceil(width);
if (targetWidth % 2 === 1) targetWidth += 1;
let targetHeight = Math.ceil(height);
if (targetHeight % 2 === 1) targetHeight += 1;
// We have to set the style properties directly because attempting to do it through a Svelte bound property results in `afterUpdate()` being triggered
floatingMenuContentDiv.style.setProperty("--even-integer-subpixel-expansion-x", `${targetWidth - width}`);
floatingMenuContentDiv.style.setProperty("--even-integer-subpixel-expansion-y", `${targetHeight - height}`);
});
});
resizeObserver.observe(floatingMenuContentDiv);
}
});
afterUpdate(() => {
// Gets the client bounds of the elements and apply relevant styles to them.
// TODO: Use DOM attribute bindings more whilst not causing recursive updates. Turning measuring on and off both causes the component to change,
// TODO: which causes the `afterUpdate()` Svelte event to fire extraneous times (hurting performance and sometimes causing an infinite loop).
if (!measuringOngoingGuard) positionAndStyleFloatingMenu();
});
function resizeObserverCallback(entries: ResizeObserverEntry[]) {
minWidthParentWidth = entries[0].contentRect.width;
}
function positionAndStyleFloatingMenu() {
if (type === "Cursor") return;
const floatingMenuContentDiv = floatingMenuContent?.div?.();
if (!self || !floatingMenuContainer || !floatingMenuContent || !floatingMenuContentDiv) return;
// Get constraint bounds generically
const constraintBounds = getConstraintBounds(self);
floatingMenuBounds = self.getBoundingClientRect();
const floatingMenuContainerBounds = floatingMenuContainer.getBoundingClientRect();
// Check if in scrollable container
const scrollableParent = self?.closest("[data-scrollable-x], [data-scrollable-y]");
const isInScrollableContainer = Boolean(scrollableParent);
// TODO: Make this work for all types. This is currently limited to tooltips because they're inherently small and transient.
// TODO: But on popovers and dropdowns, it's a bit harder to do this right. First we check if it's overflowing and flip the direction to avoid the overflow.
// TODO: But once it's flipped, if the position moves and the menu would no longer be overflowing, we're still flipped and thus unable to automatically notice the need to flip back.
// TODO: So as a result, once flipped, it stays flipped forever even if the menu spawner element is moved back away from the edge of the window.
if (type === "Tooltip") {
const floatingMenuContentBounds = floatingMenuContentDiv.getBoundingClientRect();
const overflowingTop = floatingMenuContentBounds.top - windowEdgeMargin <= constraintBounds.top;
const overflowingBottom = floatingMenuContentBounds.bottom + windowEdgeMargin >= constraintBounds.bottom;
const overflowingLeft = floatingMenuContentBounds.left - windowEdgeMargin <= constraintBounds.left;
const overflowingRight = floatingMenuContentBounds.right + windowEdgeMargin >= constraintBounds.right;
// Flip direction if overflowing the edge of the window
if (direction === "Top" && overflowingTop) direction = "Bottom";
else if (direction === "Bottom" && overflowingBottom) direction = "Top";
else if (direction === "Left" && overflowingLeft) direction = "Right";
else if (direction === "Right" && overflowingRight) direction = "Left";
}
const inParentFloatingMenu = Boolean(floatingMenuContainer.closest("[data-floating-menu-content]"));
if (!inParentFloatingMenu) {
// Required to correctly position content when scrolled (it has a `position: fixed` to prevent clipping)
// We use `.style` on a div (instead of a style DOM attribute binding) because the binding causes the `afterUpdate()` hook to call the function we're in recursively forever
let tailOffset = 0;
if (type === "Popover") tailOffset = 10;
if (type === "Tooltip") tailOffset = direction === "Bottom" ? 20 : 10;
// For menus in scrollable containers, position dynamically and center on button
if (isInScrollableContainer) {
floatingMenuContentDiv.style.position = "fixed";
const buttonCenterX = floatingMenuBounds.x + floatingMenuBounds.width / 2;
const buttonCenterY = floatingMenuBounds.y + floatingMenuBounds.height / 2;
// Set position based on direction
if (direction === "Bottom") {
floatingMenuContentDiv.style.top = `${tailOffset + floatingMenuBounds.y}px`;
floatingMenuContentDiv.style.left = `${buttonCenterX}px`;
floatingMenuContentDiv.style.bottom = "";
floatingMenuContentDiv.style.right = "";
floatingMenuContentDiv.style.transform = "translateX(-50%)";
} else if (direction === "Top") {
floatingMenuContentDiv.style.bottom = `${tailOffset + (constraintBounds.height - (floatingMenuBounds.y - constraintBounds.top))}px`;
floatingMenuContentDiv.style.left = `${buttonCenterX}px`;
floatingMenuContentDiv.style.top = "";
floatingMenuContentDiv.style.right = "";
floatingMenuContentDiv.style.transform = "translateX(-50%)";
} else if (direction === "Right") {
floatingMenuContentDiv.style.left = `${tailOffset + floatingMenuBounds.x}px`;
floatingMenuContentDiv.style.top = `${buttonCenterY}px`;
floatingMenuContentDiv.style.bottom = "";
floatingMenuContentDiv.style.right = "";
floatingMenuContentDiv.style.transform = "translateY(-50%)";
} else if (direction === "Left") {
floatingMenuContentDiv.style.right = `${tailOffset + (constraintBounds.width - (floatingMenuBounds.x - constraintBounds.left))}px`;
floatingMenuContentDiv.style.top = `${buttonCenterY}px`;
floatingMenuContentDiv.style.bottom = "";
floatingMenuContentDiv.style.left = "";
floatingMenuContentDiv.style.transform = "translateY(-50%)";
}
// Recalculate bounds after positioning
floatingMenuContentBounds = floatingMenuContentDiv.getBoundingClientRect();
const overflowingLeft = floatingMenuContentBounds.left - windowEdgeMargin <= constraintBounds.left;
const overflowingRight = floatingMenuContentBounds.right + windowEdgeMargin >= constraintBounds.right;
const overflowingTop = floatingMenuContentBounds.top - windowEdgeMargin <= constraintBounds.top;
const overflowingBottom = floatingMenuContentBounds.bottom + windowEdgeMargin >= constraintBounds.bottom;
// Adjust for overflow
if (direction === "Bottom" || direction === "Top") {
if (overflowingLeft) {
const overflow = windowEdgeMargin + constraintBounds.left - floatingMenuContentBounds.left;
floatingMenuContentDiv.style.left = `${buttonCenterX + overflow}px`;
} else if (overflowingRight) {
const overflow = floatingMenuContentBounds.right + windowEdgeMargin - constraintBounds.right;
floatingMenuContentDiv.style.left = `${buttonCenterX - overflow}px`;
}
} else if (direction === "Left" || direction === "Right") {
if (overflowingTop) {
const overflow = windowEdgeMargin + constraintBounds.top - floatingMenuContentBounds.top;
floatingMenuContentDiv.style.top = `${buttonCenterY + overflow}px`;
} else if (overflowingBottom) {
const overflow = floatingMenuContentBounds.bottom + windowEdgeMargin - constraintBounds.bottom;
floatingMenuContentDiv.style.top = `${buttonCenterY - overflow}px`;
}
}
} else {
// Standard positioning for non-scrollable contexts
floatingMenuContentDiv.style.position = "fixed";
if (direction === "Bottom") floatingMenuContentDiv.style.top = `${tailOffset + floatingMenuBounds.y}px`;
if (direction === "Top") floatingMenuContentDiv.style.bottom = `${tailOffset + (constraintBounds.height - floatingMenuBounds.y)}px`;
if (direction === "Right") floatingMenuContentDiv.style.left = `${tailOffset + floatingMenuBounds.x}px`;
if (direction === "Left") floatingMenuContentDiv.style.right = `${tailOffset + (constraintBounds.width - floatingMenuBounds.x)}px`;
}
// Required to correctly position tail when scrolled (it has a `position: fixed` to prevent clipping)
// We use `.style` on a div (instead of a style DOM attribute binding) because the binding causes the `afterUpdate()` hook to call the function we're in recursively forever
if (tail) {
const buttonCenterX = floatingMenuBounds.x + floatingMenuBounds.width / 2;
const buttonCenterY = floatingMenuBounds.y + floatingMenuBounds.height / 2;
const dialogBounds = floatingMenuContentDiv.getBoundingClientRect();
const borderRadius = 4;
const tailWidth = 12;
if (direction === "Bottom" || direction === "Top") {
const minX = dialogBounds.left + borderRadius + tailWidth / 2;
const maxX = dialogBounds.right - borderRadius - tailWidth / 2;
const constrainedX = Math.max(minX, Math.min(maxX, buttonCenterX));
if (direction === "Bottom") {
tail.style.top = `${floatingMenuBounds.y}px`;
tail.style.left = `${constrainedX}px`;
} else {
tail.style.bottom = `${constraintBounds.height - floatingMenuBounds.y}px`;
tail.style.left = `${constrainedX}px`;
}
} else if (direction === "Left" || direction === "Right") {
const minY = dialogBounds.top + borderRadius + tailWidth / 2;
const maxY = dialogBounds.bottom - borderRadius - tailWidth / 2;
const constrainedY = Math.max(minY, Math.min(maxY, buttonCenterY));
if (direction === "Right") {
tail.style.left = `${floatingMenuBounds.x}px`;
tail.style.top = `${constrainedY}px`;
} else {
tail.style.right = `${constraintBounds.width - floatingMenuBounds.x}px`;
tail.style.top = `${constrainedY}px`;
}
}
}
}
// Handle overflow for non-scrollable contexts
if (!isInScrollableContainer) {
floatingMenuContentBounds = floatingMenuContentDiv.getBoundingClientRect();
const overflowingLeft = floatingMenuContentBounds.left - windowEdgeMargin <= constraintBounds.left;
const overflowingRight = floatingMenuContentBounds.right + windowEdgeMargin >= constraintBounds.right;
const overflowingTop = floatingMenuContentBounds.top - windowEdgeMargin <= constraintBounds.top;
const overflowingBottom = floatingMenuContentBounds.bottom + windowEdgeMargin >= constraintBounds.bottom;
type Edge = "Top" | "Bottom" | "Left" | "Right";
let zeroedBorderVertical: Edge | undefined;
let zeroedBorderHorizontal: Edge | undefined;
if (direction === "Top" || direction === "Bottom") {
zeroedBorderVertical = direction === "Top" ? "Bottom" : "Top";
// We use `.style` on a div (instead of a style DOM attribute binding) because the binding causes the `afterUpdate()` hook to call the function we're in recursively forever
if (overflowingLeft) {
floatingMenuContentDiv.style.left = `${windowEdgeMargin}px`;
if (constraintBounds.left + floatingMenuContainerBounds.left === 12) zeroedBorderHorizontal = "Left";
}
if (overflowingRight) {
floatingMenuContentDiv.style.right = `${windowEdgeMargin}px`;
if (constraintBounds.right - floatingMenuContainerBounds.right === 12) zeroedBorderHorizontal = "Right";
}
}
if (direction === "Left" || direction === "Right") {
zeroedBorderHorizontal = direction === "Left" ? "Right" : "Left";
// We use `.style` on a div (instead of a style DOM attribute binding) because the binding causes the `afterUpdate()` hook to call the function we're in recursively forever
if (overflowingTop) {
floatingMenuContentDiv.style.top = `${windowEdgeMargin}px`;
if (constraintBounds.top + floatingMenuContainerBounds.top === 12) zeroedBorderVertical = "Top";
}
if (overflowingBottom) {
floatingMenuContentDiv.style.bottom = `${windowEdgeMargin}px`;
if (constraintBounds.bottom - floatingMenuContainerBounds.bottom === 12) zeroedBorderVertical = "Bottom";
}
}
// Remove the rounded corner from the content where the tail perfectly meets the corner
if (displayTail && windowEdgeMargin === 6 && zeroedBorderVertical && zeroedBorderHorizontal) {
// We use `.style` on a div (instead of a style DOM attribute binding) because the binding causes the `afterUpdate()` hook to call the function we're in recursively forever
switch (`${zeroedBorderVertical}${zeroedBorderHorizontal}`) {
case "TopLeft":
floatingMenuContentDiv.style.borderTopLeftRadius = "0";
break;
case "TopRight":
floatingMenuContentDiv.style.borderTopRightRadius = "0";
break;
case "BottomLeft":
floatingMenuContentDiv.style.borderBottomLeftRadius = "0";
break;
case "BottomRight":
floatingMenuContentDiv.style.borderBottomRightRadius = "0";
break;
default:
break;
}
}
}
}
export function div(): HTMLDivElement | undefined {
return self;
}
// To be called by the parent component. Measures the actual width of the floating menu content element and returns it in a promise.
export async function measureAndEmitNaturalWidth() {
if (!measuringOngoingGuard) return;
// Wait for the changed content which fired the `afterUpdate()` Svelte event to be put into the DOM
await tick();
// Wait until all fonts have been loaded and rendered so measurements of content involving text are accurate
await document.fonts.ready;
// Make the component show itself with 0 min-width so it can be measured, and wait until the values have been updated to the DOM
measuringOngoing = true;
measuringOngoingGuard = true;
await tick();
// Measure the width of the floating menu content element, if it's currently visible
// The result will be `undefined` if the menu is invisible, perhaps because an ancestor component is hidden with a falsy Svelte template if condition
const naturalWidth: number | undefined = floatingMenuContent?.div?.()?.clientWidth;
// Turn off measuring mode for the component, which triggers another call to the `afterUpdate()` Svelte event, so we can turn off the protection after that has happened
measuringOngoing = false;
await tick();
measuringOngoingGuard = false;
// Notify the parent about the measured natural width
if (naturalWidth !== undefined && naturalWidth >= 0) {
dispatch("naturalWidth", naturalWidth);
}
}
function pointerMoveHandler(e: PointerEvent) {
// This element and the element being hovered over
const target = e.target as HTMLElement | undefined;
// Get the spawner element (that which is clicked to spawn this floating menu)
// Assumes the spawner is a sibling of this FloatingMenu component
const ownSpawner: HTMLElement | undefined = self?.parentElement?.querySelector(":scope > [data-floating-menu-spawner]") || undefined;
// Get the spawner element containing whatever element the user is hovering over now, if there is one
const targetSpawner: HTMLElement | undefined = target?.closest?.("[data-floating-menu-spawner]") || undefined;
// HOVER TRANSFER
// Transfer from this open floating menu to a sibling floating menu if the pointer hovers to a valid neighboring floating menu spawner
hoverTransfer(self, ownSpawner, targetSpawner);
// POINTER STRAY
// Close the floating menu if the pointer has strayed far enough from its bounds (and it's not hovering over its own spawner)
const notHoveringOverOwnSpawner = ownSpawner !== targetSpawner;
if (strayCloses && notHoveringOverOwnSpawner && isPointerEventOutsideFloatingMenu(e, POINTER_STRAY_DISTANCE)) {
// TODO: Extend this rectangle bounds check to all submenu bounds up the DOM tree since currently submenus disappear
// TODO: with zero stray distance if the cursor is further than the stray distance from only the top-level menu
dispatch("open", false);
}
// Clean up any messes from lost pointerup events
const BUTTONS_LEFT = 0b0000_0001;
const eventIncludesLmb = Boolean(e.buttons & BUTTONS_LEFT);
if (!open && !eventIncludesLmb) {
pointerStillDown = false;
window.removeEventListener("pointerup", pointerUpHandler);
}
}
function hoverTransfer(self: HTMLDivElement | undefined, ownSpawner: HTMLElement | undefined, targetSpawner: HTMLElement | undefined) {
// Algorithm pseudo-code to detect and transfer to hover-transferrable floating menu spawners
// Accompanying diagram: <https://files.keavon.com/-/SpringgreenKnownXantus/capture.png>
//
// Check our own parent for descendant spawners
// Filter out ourself and our children
// Filter out all with a different distance than our own distance from the currently-being-checked parent
// How many left?
// None -> go up a level and repeat
// Some -> is one of them the target?
// Yes -> click it and terminate
// No -> do nothing and terminate
// Helper function that gets used below
const getDepthFromAncestor = (item: Element, ancestor: Element): number | undefined => {
let depth = 1;
let parent = item.parentElement || undefined;
while (parent) {
if (parent === ancestor) return depth;
parent = parent.parentElement || undefined;
depth += 1;
}
return undefined;
};
// A list of all the descendant spawners: the spawner for this floating menu plus any spawners belonging to widgets inside this floating menu
const ownDescendantMenuSpawners = Array.from(self?.parentElement?.querySelectorAll("[data-floating-menu-spawner]") || []);
// Start with the parent of the spawner for this floating menu and keep widening the search for any other valid spawners that are hover-transferrable
let currentAncestor = (targetSpawner && ownSpawner?.parentElement) || undefined;
while (currentAncestor) {
// If the current ancestor blocks hover transfer, stop searching
if (currentAncestor.hasAttribute("data-block-hover-transfer")) break;
const ownSpawnerDepthFromCurrentAncestor = ownSpawner && getDepthFromAncestor(ownSpawner, currentAncestor);
const currentAncestor2 = currentAncestor; // This duplicate variable avoids an ESLint warning
// Get the list of descendant spawners and filter out invalid possibilities for spawners that are hover-transferrable
const listOfDescendantSpawners = Array.from(currentAncestor?.querySelectorAll("[data-floating-menu-spawner]") || []);
const filteredListOfDescendantSpawners = listOfDescendantSpawners.filter((item: Element): boolean => {
// Filter away ourself and our descendants
const notOurself = !ownDescendantMenuSpawners.includes(item);
// And filter away unequal depths from the current ancestor
const notUnequalDepths = notOurself && getDepthFromAncestor(item, currentAncestor2) === ownSpawnerDepthFromCurrentAncestor;
// And filter away descendants that explicitly disable hover transfer
return notUnequalDepths && !(item instanceof HTMLElement && item.hasAttribute("data-block-hover-transfer"));
});
// If none were found, widen the search by a level and keep trying (or stop looping if the root was reached)
if (filteredListOfDescendantSpawners.length === 0) {
currentAncestor = currentAncestor?.parentElement || undefined;
}
// Stop after the first non-empty set was found
else {
const foundTarget = filteredListOfDescendantSpawners.find((item: Element): boolean => item === targetSpawner);
// If the currently hovered spawner is one of the found valid hover-transferrable spawners, swap to it by clicking on it
if (foundTarget) {
dispatch("open", false);
(foundTarget as HTMLElement).click();
}
// In either case, we are done searching
break;
}
}
}
function keyDownHandler(e: KeyboardEvent) {
if (escapeCloses && e.key === "Escape") {
setTimeout(() => {
if (!floatingMenuContainer?.querySelector("[data-floating-menu-content][data-escape-does-not-close]")) {
dispatch("open", false);
}
}, 0);
// Find the parent floating menu and prevent it from also closing with the escape key when this floating menu does
if (self) preventEscapeClosingParentFloatingMenu(self);
}
}
function pointerDownHandler(e: PointerEvent) {
// Close the floating menu if the pointer clicked outside the floating menu (but within stray distance)
if (isPointerEventOutsideFloatingMenu(e)) {
dispatch("open", false);
// Track if the left pointer button is now down so its later click event can be canceled
const eventIsForLmb = e.button === BUTTON_LEFT;
if (eventIsForLmb) pointerStillDown = true;
}
}
function pointerUpHandler(e: PointerEvent) {
const eventIsForLmb = e.button === BUTTON_LEFT;
if (pointerStillDown && eventIsForLmb) {
// Clean up self
pointerStillDown = false;
window.removeEventListener("pointerup", pointerUpHandler);
// Prevent the click event from firing, which would normally occur right after this pointerup event
window.addEventListener("click", clickHandlerCapture, true);
}
}
function clickHandlerCapture(e: MouseEvent) {
// Stop the click event from reopening this floating menu if the click event targets the floating menu's button
e.stopPropagation();
// Clean up self
window.removeEventListener("click", clickHandlerCapture, true);
}
function isPointerEventOutsideFloatingMenu(e: PointerEvent, extraDistanceAllowed = 0): boolean {
// Consider all child menus as well as the top-level one
const allContainedFloatingMenus = [...(self?.querySelectorAll("[data-floating-menu-content]") || [])];
return !allContainedFloatingMenus.find((element) => !isPointerEventOutsideMenuElement(e, element, extraDistanceAllowed));
}
function isPointerEventOutsideMenuElement(e: PointerEvent, element: Element, extraDistanceAllowed = 0): boolean {
const floatingMenuBounds = element.getBoundingClientRect();
if (floatingMenuBounds.left - e.clientX >= extraDistanceAllowed) return true;
if (e.clientX - floatingMenuBounds.right >= extraDistanceAllowed) return true;
if (floatingMenuBounds.top - e.clientY >= extraDistanceAllowed) return true;
if (e.clientY - floatingMenuBounds.bottom >= extraDistanceAllowed) return true;
return false;
}
</script>
<div
class={`floating-menu ${direction.toLowerCase()} ${type.toLowerCase()} ${className} ${extraClasses}`.trim()}
style={`${styleName} ${extraStyles}`.trim() || undefined}
bind:this={self}
{...$$restProps}
>
{#if displayTail}
<div class="tail" bind:this={tail}></div>
{/if}
{#if displayContainer}
<div class="floating-menu-container" bind:this={floatingMenuContainer}>
<LayoutCol class="floating-menu-content" styles={{ "min-width": minWidthStyleValue }} {scrollableY} bind:this={floatingMenuContent} data-floating-menu-content>
<slot />
</LayoutCol>
</div>
{/if}
</div>
<style lang="scss" global>
.floating-menu {
position: absolute;
width: 0;
height: 0;
display: flex;
// Floating menus begin at a z-index of 1000
z-index: 1000;
--floating-menu-content-offset: 0;
.tail {
// Put the tail above the floating menu's shadow
z-index: 10;
// Draw over the application without being clipped by the containing panel's `overflow: hidden`
position: fixed;
&,
&::before {
width: 0;
height: 0;
border-style: solid;
}
&::before {
content: "";
position: absolute;
}
}
.floating-menu-container {
display: flex;
.floating-menu-content {
background: var(--color-2-mildblack);
box-shadow: rgba(var(--color-0-black-rgb), 0.5) 0 2px 4px;
border: 1px solid var(--color-3-darkgray);
border-radius: 4px;
color: var(--color-e-nearwhite);
font-size: inherit;
padding: 8px;
z-index: 0;
// Draw over the application without being clipped by the containing panel's `overflow: hidden`
position: fixed;
// Counteract the rightward shift caused by the border
margin-left: -1px;
}
}
&.dropdown {
&.top {
width: 100%;
left: 0;
top: 0;
}
&.bottom {
width: 100%;
left: 0;
bottom: 0;
}
&.left {
height: 100%;
top: 0;
left: 0;
}
&.right {
height: 100%;
top: 0;
right: 0;
}
&.topleft {
top: 0;
left: 0;
margin-top: -4px;
}
&.topright {
top: 0;
right: 0;
margin-top: -4px;
}
&.topleft {
bottom: 0;
left: 0;
margin-bottom: -4px;
}
&.topright {
bottom: 0;
right: 0;
margin-bottom: -4px;
}
}
&.top.dropdown .floating-menu-container,
&.bottom.dropdown .floating-menu-container {
justify-content: left;
}
&.popover {
--floating-menu-content-offset: 10px;
}
&.cursor .floating-menu-container .floating-menu-content {
background: none;
box-shadow: none;
border-radius: 0;
padding: 0;
}
&.center {
justify-content: center;
align-items: center;
> .floating-menu-container > .floating-menu-content {
transform: translate(-50%, -50%);
}
}
&.top,
&.bottom {
flex-direction: column;
}
&.top .tail,
&.topleft .tail,
&.topright .tail {
border-color: var(--color-3-darkgray) transparent transparent transparent;
&::before {
border-color: var(--color-2-mildblack) transparent transparent transparent;
bottom: 0;
}
&,
&::before {
border-width: 8px 6px 0 6px;
margin-left: -6px;
margin-bottom: 2px;
}
}
&.bottom .tail,
&.bottomleft .tail,
&.bottomright .tail {
border-color: transparent transparent var(--color-3-darkgray) transparent;
&::before {
border-color: transparent transparent var(--color-2-mildblack) transparent;
top: 0;
}
&,
&::before {
border-width: 0 6px 8px 6px;
margin-left: -6px;
margin-top: 2px;
}
}
&.left .tail {
border-color: transparent transparent transparent var(--color-3-darkgray);
&::before {
border-color: transparent transparent transparent var(--color-2-mildblack);
right: 0;
}
&,
&::before {
border-width: 6px 0 6px 8px;
margin-top: -6px;
margin-right: 2px;
}
}
&.right .tail {
border-color: transparent var(--color-3-darkgray) transparent transparent;
&::before {
border-color: transparent var(--color-2-mildblack) transparent transparent;
left: 0;
}
&,
&::before {
border-width: 6px 8px 6px 0;
margin-top: -6px;
margin-left: 2px;
}
}
&.top .floating-menu-container {
justify-content: center;
margin-bottom: var(--floating-menu-content-offset);
}
&.bottom .floating-menu-container {
justify-content: center;
margin-top: var(--floating-menu-content-offset);
}
&.left .floating-menu-container {
align-items: center;
margin-right: var(--floating-menu-content-offset);
}
&.right .floating-menu-container {
align-items: center;
margin-left: var(--floating-menu-content-offset);
}
}
</style>