Massive/ViewBest.tsx

85 lines
2.7 KiB
TypeScript
Raw Normal View History

2022-07-11 01:00:17 +00:00
import {
RouteProp,
useFocusEffect,
useNavigation,
useRoute,
} from '@react-navigation/native';
2022-07-09 01:48:45 +00:00
import * as shape from 'd3-shape';
2022-07-11 01:00:17 +00:00
import React, {useCallback, useContext, useEffect, useState} from 'react';
import {Text, View} from 'react-native';
import {IconButton} from 'react-native-paper';
import {Grid, LineChart, XAxis, YAxis} from 'react-native-svg-charts';
2022-07-08 12:11:10 +00:00
import {DatabaseContext} from './App';
2022-07-11 01:00:17 +00:00
import {BestPageParams} from './BestPage';
import Set from './set';
import {formatMonth} from './time';
2022-07-08 12:11:10 +00:00
2022-07-11 01:00:17 +00:00
export default function ViewBest() {
const {params} = useRoute<RouteProp<BestPageParams, 'ViewBest'>>();
const [sets, setSets] = useState<Set[]>([]);
2022-07-08 12:11:10 +00:00
const db = useContext(DatabaseContext);
2022-07-11 01:00:17 +00:00
const navigation = useNavigation();
useFocusEffect(
useCallback(() => {
navigation.getParent()?.setOptions({
headerLeft: () => (
<IconButton icon="arrow-back" onPress={() => navigation.goBack()} />
),
title: params.best.name,
});
}, [navigation, params.best.name]),
);
2022-07-08 12:11:10 +00:00
useEffect(() => {
const selectBest = `
SELECT max(weight) AS weight, STRFTIME('%Y-%m-%d', created) as created, unit
FROM sets
WHERE name = ?
GROUP BY name, STRFTIME('%Y-%m-%d', created)
`;
const refresh = async () => {
2022-07-11 01:00:17 +00:00
const [result] = await db.executeSql(selectBest, [params.best.name]);
if (result.rows.length === 0) return;
console.log(`${ViewBest.name}.${refresh.name}:`, result.rows.raw());
2022-07-11 01:00:17 +00:00
setSets(result.rows.raw());
};
2022-07-08 12:11:10 +00:00
refresh();
2022-07-11 01:00:17 +00:00
}, [params.best.name, db]);
2022-07-11 01:00:17 +00:00
const axesSvg = {fontSize: 10, fill: 'grey'};
const verticalContentInset = {top: 10, bottom: 10};
const xAxisHeight = 30;
2022-07-08 12:11:10 +00:00
return (
2022-07-11 01:00:17 +00:00
<View style={{padding: 10}}>
<Text>Best weight per day</Text>
<View style={{height: 200, padding: 20, flexDirection: 'row'}}>
<YAxis
data={sets.map(set => set.weight)}
style={{marginBottom: xAxisHeight}}
contentInset={verticalContentInset}
svg={axesSvg}
formatLabel={value => `${value}${sets[0].unit}`}
/>
<View style={{flex: 1, marginLeft: 10}}>
<LineChart
style={{flex: 1}}
data={sets.map(set => set.weight)}
contentInset={verticalContentInset}
curve={shape.curveNatural}
svg={{stroke: 'rgb(134, 65, 244)'}}>
<Grid />
</LineChart>
<XAxis
style={{marginHorizontal: -10, height: xAxisHeight}}
data={sets}
formatLabel={(_value, index) => formatMonth(sets[index].created)}
contentInset={{left: 10, right: 10}}
svg={axesSvg}
/>
</View>
</View>
</View>
2022-07-08 12:11:10 +00:00
);
}