Files
jellyfin-audio-player/src/screens/Music/stacks/Albums.tsx

201 lines
7.9 KiB
TypeScript
Raw Normal View History

2020-06-25 18:07:44 +02:00
import React, { useCallback, useEffect, useRef, PureComponent, ReactText } from 'react';
2020-06-21 10:30:41 +02:00
import { useGetImage } from 'utility/JellyfinApi';
2020-06-17 14:58:04 +02:00
import { Album, NavigationProp } from '../types';
2020-06-25 18:07:44 +02:00
import { Text, SafeAreaView, SectionList, View } from 'react-native';
2020-06-17 14:58:04 +02:00
import { useDispatch } from 'react-redux';
import { useNavigation } from '@react-navigation/native';
2020-06-20 23:10:19 +02:00
import { differenceInDays } from 'date-fns';
2020-06-21 10:30:41 +02:00
import { useTypedSelector } from 'store';
import { fetchAllAlbums } from 'store/music/actions';
import { ALBUM_CACHE_AMOUNT_OF_DAYS } from 'CONSTANTS';
import TouchableHandler from 'components/TouchableHandler';
2020-06-21 13:02:23 +02:00
import ListContainer from './components/ListContainer';
import AlbumImage, { AlbumItem } from './components/AlbumImage';
2020-06-25 18:07:44 +02:00
import { selectAlbumsByAlphabet, SectionedId } from 'store/music/selectors';
import AlphabetScroller from 'components/AlphabetScroller';
import { EntityId } from '@reduxjs/toolkit';
interface VirtualizedItemInfo {
section: SectionedId,
// Key of the section or combined key for section + item
key: string,
// Relative index within the section
index: number,
// True if this is the section header
header?: boolean,
leadingItem?: EntityId,
leadingSection?: SectionedId,
trailingItem?: EntityId,
trailingSection?: SectionedId,
}
type VirtualizedSectionList = { _subExtractor: (index: number) => VirtualizedItemInfo };
function generateSection({ section }: { section: SectionedId }) {
return (
<SectionHeading label={section.label} />
);
}
class SectionHeading extends PureComponent<{ label: string }> {
render() {
const { label } = this.props;
return (
<View style={{ backgroundColor: '#f6f6f6', borderBottomColor: '#eee', borderBottomWidth: 1, height: 50, justifyContent: 'center' }}>
<Text style={{ fontSize: 24, fontWeight: 'bold'}}>{label}</Text>
</View>
);
}
}
interface GeneratedAlbumItemProps {
id: ReactText;
imageUrl: string;
name: string;
artist: string;
onPress: (id: string) => void;
}
class GeneratedAlbumItem extends PureComponent<GeneratedAlbumItemProps> {
render() {
const { id, imageUrl, name, artist, onPress } = this.props;
return (
<TouchableHandler id={id as string} onPress={onPress}>
<AlbumItem>
<AlbumImage source={{ uri: imageUrl }} />
<Text numberOfLines={1}>{name}</Text>
<Text numberOfLines={1} style={{ opacity: 0.5 }}>{artist}</Text>
</AlbumItem>
</TouchableHandler>
);
}
}
// const getItemLayout: any = sectionListGetItemLayout({
// getItemHeight: (rowData, sectionIndex, rowIndex) => {
// console.log(sectionIndex, rowIndex, rowData);
// if (sectionIndex === 0) { return 0; }
// else if (rowIndex % 2 > 0) { return 0; }
// return 220;
// },
// getSectionHeaderHeight: () => 50,
// // getSeparatorHeight: () => 1 / PixelRatio.get(),
// // listHeaderHeight: 0,
// });
2020-06-16 17:51:51 +02:00
2020-06-17 14:58:04 +02:00
const Albums: React.FC = () => {
// Retrieve data from store
2020-06-21 13:02:23 +02:00
const { entities: albums } = useTypedSelector((state) => state.music.albums);
2020-06-17 14:58:04 +02:00
const isLoading = useTypedSelector((state) => state.music.albums.isLoading);
2020-06-20 23:10:19 +02:00
const lastRefreshed = useTypedSelector((state) => state.music.lastRefreshed);
2020-06-25 18:07:44 +02:00
const sections = useTypedSelector(selectAlbumsByAlphabet);
2020-06-16 17:51:51 +02:00
2020-06-17 14:58:04 +02:00
// Initialise helpers
const dispatch = useDispatch();
const navigation = useNavigation<NavigationProp>();
const getImage = useGetImage();
2020-06-25 18:07:44 +02:00
const listRef = useRef<SectionList<EntityId>>(null);
const getItemLayout = useCallback((data: SectionedId[] | null, index: number): { offset: number, length: number, index: number } => {
// We must wait for the ref to become available before we can use the
// native item retriever in VirtualizedSectionList
if (!listRef.current) {
return { offset: 0, length: 0, index };
}
// Retrieve the right item info
// @ts-ignore
const wrapperListRef = (listRef.current?._wrapperListRef) as VirtualizedSectionList;
const info: VirtualizedItemInfo = wrapperListRef._subExtractor(index);
const { index: itemIndex, header, key } = info;
const sectionIndex = parseInt(key.split(':')[0]);
// We can then determine the "length" (=height) of this item. Header items
// end up with an itemIndex of -1, thus are easy to identify.
const length = header ? 50 : (itemIndex % 2 === 0 ? 220 : 0);
// We'll also need to account for any unevenly-ended lists up until the
// current item.
const previousRows = data?.filter((row, i) => i < sectionIndex)
.reduce((sum, row) => sum + Math.ceil(row.data.length / 2), 0) || 0;
// We must also calcuate the offset, total distance from the top of the
// screen. First off, we'll account for each sectionIndex that is shown up
// until now. This only includes the heading for the current section if the
// item is not the section header
const headingOffset = 50 * (header ? sectionIndex : sectionIndex + 1);
const currentRows = itemIndex > 1 ? Math.ceil((itemIndex + 1) / 2) : 0;
const itemOffset = 220 * (previousRows + currentRows);
const offset = headingOffset + itemOffset;
// console.log(index, sectionIndex, itemIndex, previousRows, currentRows, offset);
return { index, length, offset };
}, [listRef]);
2020-06-16 17:51:51 +02:00
2020-06-17 14:58:04 +02:00
// Set callbacks
const retrieveData = useCallback(() => dispatch(fetchAllAlbums()), [dispatch]);
const selectAlbum = useCallback((id: string) => navigation.navigate('Album', { id, album: albums[id] as Album }), [navigation, albums]);
2020-06-25 18:07:44 +02:00
const selectLetter = useCallback((sectionIndex: number) => {
listRef.current?.scrollToLocation({ sectionIndex, itemIndex: 0, animated: false, });
}, [listRef]);
const generateItem = ({ item, index, section }: { item: EntityId, index: number, section: SectionedId }) => {
if (index % 2 === 1) {
return null;
}
const nextItem = section.data[index + 1];
return (
<View style={{ flexDirection: 'row' }}>
<GeneratedAlbumItem
id={item}
imageUrl={getImage(item as string)}
name={albums[item]?.Name || ''}
artist={albums[item]?.AlbumArtist || ''}
onPress={selectAlbum}
/>
{albums[nextItem] &&
<GeneratedAlbumItem
id={nextItem}
imageUrl={getImage(nextItem as string)}
name={albums[nextItem]?.Name || ''}
artist={albums[nextItem]?.AlbumArtist || ''}
onPress={selectAlbum}
/>
}
</View>
);
};
2020-06-17 14:58:04 +02:00
// Retrieve data on mount
2020-06-20 23:10:19 +02:00
useEffect(() => {
2020-06-21 10:30:41 +02:00
// GUARD: Only refresh this API call every set amounts of days
2020-06-20 23:10:19 +02:00
if (!lastRefreshed || differenceInDays(lastRefreshed, new Date()) > ALBUM_CACHE_AMOUNT_OF_DAYS) {
retrieveData();
}
}, []);
2020-06-17 14:58:04 +02:00
return (
<SafeAreaView>
2020-06-21 13:02:23 +02:00
<ListContainer>
2020-06-25 18:07:44 +02:00
<AlphabetScroller onSelect={selectLetter} />
<SectionList
sections={sections}
2020-06-17 14:58:04 +02:00
refreshing={isLoading}
onRefresh={retrieveData}
2020-06-25 18:07:44 +02:00
getItemLayout={getItemLayout}
keyExtractor={(d) => d as string}
ref={listRef}
onScrollToIndexFailed={console.log}
renderSectionHeader={generateSection}
renderItem={generateItem}
2020-06-17 14:58:04 +02:00
/>
2020-06-21 13:02:23 +02:00
</ListContainer>
2020-06-17 14:58:04 +02:00
</SafeAreaView>
);
};
2020-06-16 17:51:51 +02:00
export default Albums;