Add "performant" recent album view

This commit is contained in:
Lei Nelissen
2020-06-25 18:07:44 +02:00
parent 623e267b52
commit 80ff88c3b2
11 changed files with 321 additions and 38 deletions

View File

@@ -1,7 +1,7 @@
import React, { useCallback, useEffect } from 'react';
import React, { useCallback, useEffect, useRef, PureComponent, ReactText } from 'react';
import { useGetImage } from 'utility/JellyfinApi';
import { Album, NavigationProp } from '../types';
import { Text, SafeAreaView, FlatList } from 'react-native';
import { Text, SafeAreaView, SectionList, View } from 'react-native';
import { useDispatch } from 'react-redux';
import { useNavigation } from '@react-navigation/native';
import { differenceInDays } from 'date-fns';
@@ -11,24 +11,164 @@ import { ALBUM_CACHE_AMOUNT_OF_DAYS } from 'CONSTANTS';
import TouchableHandler from 'components/TouchableHandler';
import ListContainer from './components/ListContainer';
import AlbumImage, { AlbumItem } from './components/AlbumImage';
import { useAlbumsByArtist } from 'store/music/selectors';
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,
// });
const Albums: React.FC = () => {
// Retrieve data from store
const { entities: albums } = useTypedSelector((state) => state.music.albums);
const ids = useAlbumsByArtist();
const isLoading = useTypedSelector((state) => state.music.albums.isLoading);
const lastRefreshed = useTypedSelector((state) => state.music.lastRefreshed);
const sections = useTypedSelector(selectAlbumsByAlphabet);
// Initialise helpers
const dispatch = useDispatch();
const navigation = useNavigation<NavigationProp>();
const getImage = useGetImage();
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]);
// Set callbacks
const retrieveData = useCallback(() => dispatch(fetchAllAlbums()), [dispatch]);
const selectAlbum = useCallback((id: string) => navigation.navigate('Album', { id, album: albums[id] as Album }), [navigation, albums]);
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>
);
};
// Retrieve data on mount
useEffect(() => {
// GUARD: Only refresh this API call every set amounts of days
@@ -40,21 +180,17 @@ const Albums: React.FC = () => {
return (
<SafeAreaView>
<ListContainer>
<FlatList
data={ids as string[]}
<AlphabetScroller onSelect={selectLetter} />
<SectionList
sections={sections}
refreshing={isLoading}
onRefresh={retrieveData}
numColumns={2}
keyExtractor={d => d}
renderItem={({ item }) => (
<TouchableHandler id={item} onPress={selectAlbum}>
<AlbumItem>
<AlbumImage source={{ uri: getImage(item) }} />
<Text>{albums[item]?.Name}</Text>
<Text style={{ opacity: 0.5 }}>{albums[item]?.AlbumArtist}</Text>
</AlbumItem>
</TouchableHandler>
)}
getItemLayout={getItemLayout}
keyExtractor={(d) => d as string}
ref={listRef}
onScrollToIndexFailed={console.log}
renderSectionHeader={generateSection}
renderItem={generateItem}
/>
</ListContainer>
</SafeAreaView>

View File

@@ -7,6 +7,7 @@ const Screen = Dimensions.get('screen');
export const AlbumItem = styled.View`
width: ${Screen.width / 2 - 10}px;
padding: 10px;
height: 220px;
`;
const AlbumImage = styled(FastImage)`