xref: /MusicFree/src/components/musicList/index.tsx (revision ea6d708f22409666b768cda1107ea1066b213247)
1import React from 'react';
2import {FlatListProps, StyleSheet} from 'react-native';
3import rpx from '@/utils/rpx';
4import MusicQueue from '@/core/musicQueue';
5import {FlatList} from 'react-native-gesture-handler';
6
7import MusicItem from '../mediaItem/musicItem';
8import Empty from '../base/empty';
9
10interface IMusicListProps {
11    /** 顶部 */
12    Header?: FlatListProps<IMusic.IMusicItem>['ListHeaderComponent'];
13    /** 音乐列表 */
14    musicList?: IMusic.IMusicItem[];
15    /** 所在歌单 */
16    musicSheet?: IMusic.IMusicSheetItem;
17    /** 是否展示序号 */
18    showIndex?: boolean;
19    /** 点击 */
20    onItemPress?: (
21        musicItem: IMusic.IMusicItem,
22        musicList?: IMusic.IMusicItem[],
23    ) => void;
24}
25const ITEM_HEIGHT = rpx(120);
26export default function MusicList(props: IMusicListProps) {
27    const {Header, musicList, musicSheet, showIndex, onItemPress} = props;
28
29    return (
30        <FlatList
31            style={style.wrapper}
32            ListHeaderComponent={Header}
33            ListEmptyComponent={Empty}
34            data={musicList ?? []}
35            keyExtractor={musicItem =>
36                `ml-${musicItem.id}${musicItem.platform}`
37            }
38            getItemLayout={(_, index) => ({
39                length: ITEM_HEIGHT,
40                offset: ITEM_HEIGHT * index,
41                index,
42            })}
43            renderItem={({index, item: musicItem}) => {
44                return (
45                    <MusicItem
46                        musicItem={musicItem}
47                        index={showIndex ? index + 1 : undefined}
48                        onItemPress={() => {
49                            if (onItemPress) {
50                                onItemPress(musicItem, musicList);
51                            } else {
52                                MusicQueue.playWithReplaceQueue(
53                                    musicItem,
54                                    musicList ?? [],
55                                );
56                            }
57                        }}
58                        musicSheet={musicSheet}
59                    />
60                );
61            }}
62        />
63    );
64}
65
66const style = StyleSheet.create({
67    wrapper: {
68        width: rpx(750),
69    },
70});
71