summaryrefslogtreecommitdiff
path: root/src/components/jet/action/ShelfBasedPageScrollAction.svelte
blob: 9c1c13edb399a74b926458119fea4a9f01bd26e6 (plain)
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
<script lang="ts" context="module">
    import type {
        Action,
        ShelfBasedPageScrollAction,
    } from '@jet-app/app-store/api/models';

    export function isShelfBasedPageScrollAction(
        action: Action,
    ): action is ShelfBasedPageScrollAction {
        return (
            action.$kind === 'ShelfBasedPageScrollAction' && 'shelfId' in action
        );
    }
</script>

<script lang="ts">
    import type { HTMLAnchorAttributes } from 'svelte/elements';

    interface $$Props extends HTMLAnchorAttributes {
        destination: ShelfBasedPageScrollAction;
    }

    export let destination: ShelfBasedPageScrollAction;

    function handleLinkClick(e: Event) {
        const anchorElement = e.currentTarget as HTMLAnchorElement;
        const hash = anchorElement.hash;
        const elementToScrollTo = document.querySelector(hash);
        if (!elementToScrollTo) {
            return;
        }
        elementToScrollTo.scrollIntoView({
            behavior: 'smooth',
            block: 'start',
        });
        history.replaceState(null, '', hash);
    }
</script>

{#if destination.shelfId}
    <a
        {...$$restProps}
        data-test-id="scroll-link"
        href={`#${destination.shelfId}`}
        on:click|preventDefault|stopPropagation={handleLinkClick}
    >
        <slot />
    </a>
{:else}
    <slot />
{/if}