xref: /MusicFree/src/components/musicList/index.tsx (revision ddece18e7942a667c4a0b92c4f164e9a18b0ceee)
1import React from 'react';
2import {FlatListProps} from 'react-native';
3import rpx from '@/utils/rpx';
4import MusicQueue from '@/core/musicQueue';
5
6import MusicItem from '../mediaItem/musicItem';
7import Empty from '../base/empty';
8import {FlashList} from '@shopify/flash-list';
9import ListLoading from '../base/listLoading';
10import ListReachEnd from '../base/listReachEnd';
11
12interface IMusicListProps {
13    /** 顶部 */
14    Header?: FlatListProps<IMusic.IMusicItem>['ListHeaderComponent'];
15    /** 音乐列表 */
16    musicList?: IMusic.IMusicItem[];
17    /** 所在歌单 */
18    musicSheet?: IMusic.IMusicSheetItem;
19    /** 是否展示序号 */
20    showIndex?: boolean;
21    /** 点击 */
22    onItemPress?: (
23        musicItem: IMusic.IMusicItem,
24        musicList?: IMusic.IMusicItem[],
25    ) => void;
26    loadMore?: 'loading' | 'done' | 'idle';
27    onEndReached?: () => void;
28}
29const ITEM_HEIGHT = rpx(120);
30
31/** 音乐列表 */
32export default function MusicList(props: IMusicListProps) {
33    const {
34        Header,
35        musicList,
36        musicSheet,
37        showIndex,
38        onItemPress,
39        onEndReached,
40        loadMore = 'idle',
41    } = props;
42
43    return (
44        <FlashList
45            ListHeaderComponent={Header}
46            ListEmptyComponent={loadMore !== 'loading' ? Empty : null}
47            ListFooterComponent={
48                loadMore === 'done'
49                    ? ListReachEnd
50                    : loadMore === 'loading'
51                    ? ListLoading
52                    : null
53            }
54            data={musicList ?? []}
55            keyExtractor={musicItem =>
56                `ml-${musicItem.id}${musicItem.platform}`
57            }
58            estimatedItemSize={ITEM_HEIGHT}
59            renderItem={({index, item: musicItem}) => {
60                return (
61                    <MusicItem
62                        musicItem={musicItem}
63                        index={showIndex ? index + 1 : undefined}
64                        onItemPress={() => {
65                            if (onItemPress) {
66                                onItemPress(musicItem, musicList);
67                            } else {
68                                MusicQueue.playWithReplaceQueue(
69                                    musicItem,
70                                    musicList ?? [],
71                                );
72                            }
73                        }}
74                        musicSheet={musicSheet}
75                    />
76                );
77            }}
78            onEndReached={() => {
79                if (loadMore !== 'loading') {
80                    onEndReached?.();
81                }
82            }}
83            onEndReachedThreshold={0.1}
84        />
85    );
86}
87