Massive/StartPlan.tsx

228 lines
7.3 KiB
TypeScript
Raw Normal View History

import {
NavigationProp,
RouteProp,
useFocusEffect,
useNavigation,
useRoute,
} from "@react-navigation/native";
import { useCallback, useMemo, useRef, useState } from "react";
import { FlatList, NativeModules, TextInput, View } from "react-native";
import { Button, IconButton, ProgressBar } from "react-native-paper";
import AppInput from "./AppInput";
import { getBestSet } from "./best.service";
import { PADDING } from "./constants";
import CountMany from "./count-many";
import { AppDataSource } from "./data-source";
import { getNow, setRepo, settingsRepo } from "./db";
2023-10-18 06:06:13 +00:00
import { emitter } from "./emitter";
2023-08-12 03:30:47 +00:00
import { fixNumeric } from "./fix-numeric";
2023-10-19 05:28:56 +00:00
import GymSet, { GYM_SET_CREATED } from "./gym-set";
import Settings from "./settings";
import StackHeader from "./StackHeader";
import StartPlanItem from "./StartPlanItem";
import { toast } from "./toast";
import { StackParams } from "./AppStack";
2022-10-05 10:38:52 +00:00
export default function StartPlan() {
const { params } = useRoute<RouteProp<StackParams, "StartPlan">>();
const [reps, setReps] = useState(params.first?.reps.toString() || "0");
const [weight, setWeight] = useState(params.first?.weight.toString() || "0");
const [unit, setUnit] = useState<string>(params.first?.unit || "kg");
const [selected, setSelected] = useState(0);
const [settings, setSettings] = useState<Settings>();
const [counts, setCounts] = useState<CountMany[]>();
const weightRef = useRef<TextInput>(null);
const repsRef = useRef<TextInput>(null);
const unitRef = useRef<TextInput>(null);
const workouts = useMemo(() => params.plan.workouts.split(","), [params]);
const navigation = useNavigation<NavigationProp<StackParams>>();
2022-10-05 10:38:52 +00:00
const [selection, setSelection] = useState({
start: 0,
2022-10-31 04:05:31 +00:00
end: 0,
});
const refresh = useCallback(async () => {
2022-10-31 04:05:31 +00:00
const questions = workouts
.map((workout, index) => `('${workout}',${index})`)
.join(",");
2022-10-31 04:05:31 +00:00
const select = `
SELECT workouts.name, COUNT(sets.id) as total, sets.sets
2022-10-31 04:05:31 +00:00
FROM (select 0 as name, 0 as sequence union values ${questions}) as workouts
LEFT JOIN sets ON sets.name = workouts.name
AND sets.created LIKE STRFTIME('%Y-%m-%d%%', 'now', 'localtime')
AND NOT sets.hidden
2022-10-31 04:05:31 +00:00
GROUP BY workouts.name
ORDER BY workouts.sequence
LIMIT -1
OFFSET 1
`;
const newCounts = await AppDataSource.manager.query(select);
console.log(`${StartPlan.name}.focus:`, { newCounts });
setCounts(newCounts);
}, [workouts]);
2022-10-30 02:34:17 +00:00
2022-10-31 04:05:31 +00:00
const select = useCallback(
async (index: number, newCounts?: CountMany[]) => {
setSelected(index);
if (!counts && !newCounts) return;
const workout = counts ? counts[index] : newCounts[index];
console.log(`${StartPlan.name}.next:`, { workout });
const last = await setRepo.findOne({
where: { name: workout.name },
order: { created: "desc" },
});
console.log({ last });
if (!last) return;
delete last.id;
console.log(`${StartPlan.name}.select:`, { last });
setReps(last.reps.toString());
setWeight(last.weight.toString());
setUnit(last.unit);
2022-10-31 04:05:31 +00:00
},
[counts]
);
2022-10-31 04:05:31 +00:00
useFocusEffect(
useCallback(() => {
settingsRepo.findOne({ where: {} }).then(setSettings);
refresh();
}, [refresh])
);
2022-10-05 10:38:52 +00:00
const handleSubmit = async () => {
const now = await getNow();
const workout = counts[selected];
const best = await getBestSet(workout.name);
delete best.id;
const newSet: GymSet = {
...best,
2022-10-05 10:38:52 +00:00
weight: +weight,
reps: +reps,
unit,
created: now,
2022-10-31 04:05:31 +00:00
hidden: false,
};
2023-10-18 06:06:13 +00:00
const saved = await setRepo.save(newSet);
emitter.emit(GYM_SET_CREATED, saved);
await refresh();
if (
2022-10-16 01:38:01 +00:00
settings.notify &&
(+weight > best.weight || (+reps > best.reps && +weight === best.weight))
2023-06-27 03:16:59 +00:00
) {
toast("Great work King! That's a new record.");
2023-06-27 03:16:59 +00:00
}
if (!settings.alarm) return;
const milliseconds =
Number(best.minutes) * 60 * 1000 + Number(best.seconds) * 1000;
NativeModules.AlarmModule.timer(milliseconds);
};
2022-10-05 10:38:52 +00:00
return (
<>
<StackHeader
title={params.plan.title || params.plan.days.replace(/,/g, ", ")}
>
<IconButton
onPress={() => navigation.navigate("EditPlan", { plan: params.plan })}
2023-10-19 05:28:56 +00:00
icon="pencil"
/>
</StackHeader>
<View style={{ padding: PADDING, flex: 1, flexDirection: "column" }}>
2023-06-27 03:16:59 +00:00
<View style={{ flex: 1 }}>
<View>
<AppInput
label="Reps"
keyboardType="numeric"
value={reps}
onChangeText={(newReps) => {
const fixed = fixNumeric(newReps);
setReps(fixed);
if (fixed.length !== newReps.length)
toast("Reps must be a number");
}}
onSubmitEditing={() => weightRef.current?.focus()}
selection={selection}
onSelectionChange={(e) => setSelection(e.nativeEvent.selection)}
innerRef={repsRef}
/>
<View
style={{ position: "absolute", right: 0, flexDirection: "row" }}
>
<IconButton
icon="plus"
onPress={() => setReps((Number(reps) + 1).toString())}
/>
<IconButton
icon="minus"
onPress={() => setReps((Number(reps) - 1).toString())}
/>
</View>
</View>
<View>
<AppInput
label="Weight"
keyboardType="numeric"
value={weight}
onChangeText={(newWeight) => {
const fixed = fixNumeric(newWeight);
setWeight(fixed);
if (fixed.length !== newWeight.length)
toast("Weight must be a number");
}}
onSubmitEditing={handleSubmit}
innerRef={weightRef}
blurOnSubmit
/>
<View
style={{ position: "absolute", right: 0, flexDirection: "row" }}
>
<IconButton
icon="plus"
onPress={() => setWeight((Number(weight) + 2.5).toString())}
/>
<IconButton
icon="minus"
onPress={() => setWeight((Number(weight) - 2.5).toString())}
/>
</View>
</View>
{settings?.showUnit && (
2022-12-29 00:57:19 +00:00
<AppInput
autoCapitalize="none"
label="Unit"
value={unit}
onChangeText={setUnit}
innerRef={unitRef}
/>
)}
{counts && (
<FlatList
data={counts}
2023-08-28 23:22:15 +00:00
keyExtractor={(count) => count.name}
2023-06-27 03:16:59 +00:00
renderItem={(props) => (
<View>
<StartPlanItem
{...props}
onUndo={refresh}
onSelect={select}
selected={selected}
/>
<ProgressBar
progress={(props.item.total || 0) / (props.item.sets || 3)}
/>
</View>
)}
/>
)}
</View>
2023-10-19 05:28:56 +00:00
<Button mode="outlined" icon="content-save" onPress={handleSubmit}>
Save
</Button>
2022-10-05 10:38:52 +00:00
</View>
</>
);
2022-10-05 10:38:52 +00:00
}