import { NavigationProp, RouteProp, useNavigation, useRoute, } from "@react-navigation/native"; import { useCallback, useEffect, useState } from "react"; import { ScrollView, StyleSheet, View } from "react-native"; import { Button, IconButton, Text } from "react-native-paper"; import { MARGIN, PADDING } from "./constants"; import { planRepo, setRepo } from "./db"; import { defaultSet } from "./gym-set"; import StackHeader from "./StackHeader"; import Switch from "./Switch"; import { DAYS } from "./time"; import AppInput from "./AppInput"; import { StackParams } from "./AppStack"; import { DrawerParams } from "./drawer-param-list"; export default function EditPlan() { const { params } = useRoute>(); const { plan } = params; const [title, setTitle] = useState(plan?.title); const [days, setDays] = useState( plan.days ? plan.days.split(",") : [] ); const [workouts, setWorkouts] = useState( plan.workouts ? plan.workouts.split(",") : [] ); const [names, setNames] = useState([]); const { navigate: drawerNavigate } = useNavigation>(); const { navigate: stackNavigate } = useNavigation>(); useEffect(() => { setRepo .createQueryBuilder() .select("name") .distinct(true) .orderBy("name") .getRawMany() .then((values) => { console.log(EditPlan.name, { values }); setNames(values.map((value) => value.name)); }); }, []); const save = useCallback(async () => { console.log(`${EditPlan.name}.save`, { days, workouts, plan }); if (!days || !workouts) return; const newWorkouts = workouts.filter((workout) => workout).join(","); const newDays = days.filter((day) => day).join(","); await planRepo.save({ title: title, days: newDays, workouts: newWorkouts, id: plan.id, }); }, [title, days, workouts, plan]); const toggleWorkout = useCallback( (on: boolean, name: string) => { if (on) { setWorkouts([...workouts, name]); } else { setWorkouts(workouts.filter((workout) => workout !== name)); } }, [setWorkouts, workouts] ); const toggleDay = useCallback( (on: boolean, day: string) => { if (on) { setDays([...days, day]); } else { setDays(days.filter((d) => d !== day)); } }, [setDays, days] ); return ( <> {typeof plan.id === "number" && ( { await save(); const newPlan = await planRepo.findOne({ where: { id: plan.id }, }); let first = await setRepo.findOne({ where: { name: workouts[0] }, order: { created: "desc" }, }); if (!first) first = { ...defaultSet, name: workouts[0] }; delete first.id; stackNavigate("StartPlan", { plan: newPlan, first }); }} icon="play" /> )} setTitle(value)} /> Days {DAYS.map((day) => ( toggleDay(value, day)} value={days.includes(day)} title={day} /> ))} Workouts {names.length === 0 ? ( No workouts found. ) : ( names.map((name) => ( toggleWorkout(value, name)} value={workouts.includes(name)} title={name} /> )) )} ); } const styles = StyleSheet.create({ title: { fontSize: 20, marginBottom: MARGIN, }, button: {}, });