summaryrefslogtreecommitdiffstats
path: root/apps/web-shared/src/components/menu/menu.svelte
blob: 33b11603147dc04114c1ff338aaf142c85f80bc3 (plain) (blame)
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
<script lang="ts">
    import {random_string} from "$shared/lib/helpers";

    export let id = "__menu_" + random_string(3);
    export let trigger: HTMLElement;
    export let show = false;

    let windowInnerWidth = 0;
    let windowInnerHeight = 0;
    let menu: HTMLMenuElement;

    $: if (show && menu && trigger) {
        const
            selectedTriggerPosition = trigger.getBoundingClientRect(),
            menuOnTop = (windowInnerHeight - selectedTriggerPosition.bottom) < selectedTriggerPosition.top,
            left = selectedTriggerPosition.left,
            right = (windowInnerWidth - selectedTriggerPosition.right),
            isRight = (windowInnerWidth < selectedTriggerPosition.left + menu.offsetWidth),
            vertical = menuOnTop
                ? "bottom: " + (windowInnerHeight - selectedTriggerPosition.top) + "px;"
                : "top: " + selectedTriggerPosition.bottom + "px;";

        let horizontal = isRight ? "right: " + right + "px;" : "left: " + left + "px;";

        // check right position is correct -> otherwise set left to 0
        if (isRight && (right + menu.offsetWidth) > windowInnerWidth) horizontal = ("left: " + (windowInnerWidth - menu.offsetWidth) / 2 + "px;");
        const maxHeight = menuOnTop ? selectedTriggerPosition.top - 20 : windowInnerHeight - selectedTriggerPosition.bottom - 20;
        menu.setAttribute("style", horizontal + vertical + "max-height:" + Math.floor(maxHeight) + "px;");
    }
    
    function on_window_click(event) {
        if (!event.target.closest("#" + id) && !event.target.closest("[aria-controls='" + id + "']")) show = false;
    }

    function on_window_touchend(event) {
        if (!event.target.closest("#" + id) && !event.target.closest("[aria-controls='" + id + "']")) show = false;
    }
</script>

<svelte:window
        on:click={on_window_click}
        on:touchend={on_window_touchend}
        bind:innerWidth={windowInnerWidth}
        bind:innerHeight={windowInnerHeight}
/>

<menu class="menu"
      id="{id}"
      bind:this={menu}
      class:menu--is-visible={show}
      aria-expanded="{show}"
      aria-haspopup="true">
    <slot name="options"/>
</menu>