Add "performant" recent album view
This commit is contained in:
@@ -1 +1,2 @@
|
||||
export const ALBUM_CACHE_AMOUNT_OF_DAYS = 7;
|
||||
export const ALBUM_CACHE_AMOUNT_OF_DAYS = 7;
|
||||
export const ALPHABET_LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ ';
|
||||
87
src/components/AlphabetScroller.tsx
Normal file
87
src/components/AlphabetScroller.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
import React, { useCallback, useRef, useState } from 'react';
|
||||
import styled from 'styled-components/native';
|
||||
import { ALPHABET_LETTERS } from 'CONSTANTS';
|
||||
import { View, LayoutChangeEvent } from 'react-native';
|
||||
import { TouchableWithoutFeedback, PanGestureHandler, PanGestureHandlerGestureEvent, TapGestureHandler, TapGestureHandlerGestureEvent } from 'react-native-gesture-handler';
|
||||
|
||||
interface LetterContainerProps {
|
||||
onPress: (letter: string) => void;
|
||||
letter: string;
|
||||
}
|
||||
|
||||
const LetterContainer: React.FC<LetterContainerProps> = ({ children, letter, onPress }) => {
|
||||
const handlePress = useCallback(() => {
|
||||
onPress(letter);
|
||||
}, [letter, onPress]);
|
||||
|
||||
return (
|
||||
<TouchableWithoutFeedback onPress={handlePress}>
|
||||
{children}
|
||||
</TouchableWithoutFeedback>
|
||||
);
|
||||
};
|
||||
|
||||
const Container = styled.View`
|
||||
position: absolute;
|
||||
right: 5px;
|
||||
top: 0;
|
||||
height: 100%;
|
||||
z-index: 10;
|
||||
padding: 5px;
|
||||
margin: auto 0;
|
||||
justify-content: space-around;
|
||||
`;
|
||||
|
||||
const Letter = styled.Text`
|
||||
text-align: center;
|
||||
padding: 1px 0;
|
||||
`;
|
||||
|
||||
interface Props {
|
||||
onSelect: (index: number) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* A generic component that introduces a scrolling bar on the right side of the
|
||||
* screen with all letters of the Alphabet.
|
||||
*/
|
||||
const AlphabetScroller: React.FC<Props> = ({ onSelect }) => {
|
||||
const [ height, setHeight ] = useState(0);
|
||||
const [ index, setIndex ] = useState<number>();
|
||||
|
||||
// Handler for setting the correct height for a single alphabet item
|
||||
const handleLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
setHeight(event.nativeEvent.layout.height);
|
||||
}, []);
|
||||
|
||||
// Handler for passing on a new index when it is tapped or swiped
|
||||
const handleGestureEvent = useCallback((event: PanGestureHandlerGestureEvent | TapGestureHandlerGestureEvent) => {
|
||||
const newIndex = Math.floor(event.nativeEvent.y / height);
|
||||
|
||||
if (newIndex !== index) {
|
||||
setIndex(newIndex);
|
||||
onSelect(newIndex);
|
||||
}
|
||||
}, [height, index]);
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<TapGestureHandler onHandlerStateChange={handleGestureEvent}>
|
||||
<PanGestureHandler onGestureEvent={handleGestureEvent}>
|
||||
<View>
|
||||
{ALPHABET_LETTERS.split('').map((l, i) => (
|
||||
<View
|
||||
key={l}
|
||||
onLayout={i === 0 ? handleLayout : undefined}
|
||||
>
|
||||
<Letter>{l}</Letter>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</PanGestureHandler>
|
||||
</TapGestureHandler>
|
||||
</Container>
|
||||
);
|
||||
};
|
||||
|
||||
export default AlphabetScroller;
|
||||
@@ -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>
|
||||
|
||||
@@ -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)`
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useTypedSelector } from 'store';
|
||||
import { useTypedSelector, AppState } from 'store';
|
||||
import { parseISO } from 'date-fns';
|
||||
import { Album } from './types';
|
||||
import { ALPHABET_LETTERS } from 'CONSTANTS';
|
||||
import { createSelector, EntityId } from '@reduxjs/toolkit';
|
||||
import { SectionListData } from 'react-native';
|
||||
|
||||
/**
|
||||
* Retrieves a list of the n most recent albums
|
||||
@@ -20,9 +22,11 @@ export function useRecentAlbums(amount: number) {
|
||||
return sorted.slice(0, amount);
|
||||
}
|
||||
|
||||
export function useAlbumsByArtist() {
|
||||
const albums = useTypedSelector((state) => state.music.albums.entities);
|
||||
const albumIds = useTypedSelector((state) => state.music.albums.ids);
|
||||
/**
|
||||
* Sort all albums by AlbumArtist
|
||||
*/
|
||||
function albumsByArtist(state: AppState['music']['albums']) {
|
||||
const { entities: albums, ids: albumIds } = state;
|
||||
|
||||
const sorted = [...albumIds].sort((a, b) => {
|
||||
const albumA = albums[a];
|
||||
@@ -39,4 +43,37 @@ export function useAlbumsByArtist() {
|
||||
});
|
||||
|
||||
return sorted;
|
||||
}
|
||||
}
|
||||
|
||||
export const selectAlbumsByArtist = createSelector(
|
||||
(state: AppState) => state.music.albums,
|
||||
albumsByArtist,
|
||||
);
|
||||
|
||||
export type SectionedId = SectionListData<EntityId>;
|
||||
|
||||
/**
|
||||
* Splits a set of albums into a list that is split by alphabet letters
|
||||
*/
|
||||
function splitByAlphabet(state: AppState['music']['albums']): SectionedId[] {
|
||||
const { entities: albums } = state;
|
||||
const albumIds = albumsByArtist(state);
|
||||
const sections: SectionedId[] = ALPHABET_LETTERS.split('').map((l) => ({ label: l, data: [] }));
|
||||
|
||||
albumIds.forEach((id) => {
|
||||
const album = albums[id];
|
||||
const letter = album?.AlbumArtist?.toUpperCase().charAt(0);
|
||||
const index = letter ? ALPHABET_LETTERS.indexOf(letter) : 26;
|
||||
(sections[index >= 0 ? index : 26].data as Array<EntityId>).push(id);
|
||||
});
|
||||
|
||||
return sections;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap splitByAlphabet into a memoized selector
|
||||
*/
|
||||
export const selectAlbumsByAlphabet = createSelector(
|
||||
(state: AppState) => state.music.albums,
|
||||
splitByAlphabet,
|
||||
);
|
||||
Reference in New Issue
Block a user