summaryrefslogtreecommitdiff
path: root/src/utils/shelves.ts
blob: e144f4b4cd47e896fcba24fa32fe0129f382de53 (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
52
53
54
55
56
import type {
    ShelfBasedProductPage,
    Shelf,
} from '@jet-app/app-store/api/models';
import { isProductMediaShelf } from '~/components/jet/shelf/ProductMediaShelf.svelte';

type ShelfWithExpandedMedia = Shelf & {
    expandedMedia?: ShelfWithExpandedMedia[];
};

export const getProductPageShelvesForOrdering = (
    page: ShelfBasedProductPage,
    shelfOrder: string,
): Shelf[] => {
    return (
        page.shelfOrderings[shelfOrder]
            ?.map((shelfIdentifier) => page.shelfMapping[shelfIdentifier])
            // The type system doesn't reflect this, but ordering identifier may be provided for
            // shelves that do not exist. We should probably filter those out
            .filter((shelf): shelf is Shelf => !!shelf)
    );
};

export const getProductPageShelvesWithExpandedMedia = (
    page: ShelfBasedProductPage,
): ShelfWithExpandedMedia[] => {
    const { defaultShelfOrdering = 'notPurchasedOrdering' } = page;

    const shelves = getProductPageShelvesForOrdering(
        page,
        defaultShelfOrdering,
    ) as ShelfWithExpandedMedia[];

    // find the location of the product media of selected platform in shelves
    const mainMediaShelfIndex = shelves.findIndex((shelf) =>
        isProductMediaShelf(shelf),
    );

    let expandedMedia: ShelfWithExpandedMedia[] | undefined;

    if (mainMediaShelfIndex !== -1) {
        expandedMedia = getProductPageShelvesForOrdering(
            page,
            'notPurchasedOrdering_ExpandedMedia',
        )
            .filter((shelf) => isProductMediaShelf(shelf))
            // filter out the product media shelf of selected platform to avoid duplicate shelves
            .filter(({ id }) => id !== shelves[mainMediaShelfIndex].id);
    }

    if (expandedMedia) {
        shelves[mainMediaShelfIndex].expandedMedia = expandedMedia;
    }

    return shelves;
};