Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

8.6 KB
Raw Blame
import { useEffect, useState } from 'react'
import { ActivityIndicator, Pressable, ScrollView, View } from 'react-native'
import { router } from 'expo-router'
import { ArrowLeft, BookOpen, ChevronRight, Play, Timer, Trash2, Zap } from 'lucide-react-native'
import type { Program, ProgramDay } from '@lyftr/shared'
import { activeSessionExercisesForDay, sessionNameForDay, defaultWorkoutName, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'
import { AppText, ErrorState, IconButton, Screen } from '../../../src/components/ui'
import { DayPickerSheet, pickProgramDay } from '../../../src/components/programs/DayPickerSheet'
import { client, useWorkoutSession } from '../../../src/lib/lyftr'
import { useTheme } from '../../../src/theme/useTheme'

// Port of web/pages/StartWorkout.tsx. Quick-start (blank), start-from-program, and a
// resume/discard banner for an in-progress session. Navigates to /workouts/active,
// which itself opens the gym overlay when the layout pref is 'gym'.
export default function StartWorkout() {
  const { t } = useTranslation()
  const session = useWorkoutSession((s) => s.session)
  const startSession = useWorkoutSession((s) => s.startSession)
  const cancelSession = useWorkoutSession((s) => s.cancelSession)
  const { colors, accent } = useTheme()

  const [programs, setPrograms] = useState<Program[]>([])
  const [loading, setLoading] = useState(false)
  // A UiMessage, not its sentence, so the banner follows a live language switch.
  const [error, setError] = useState<UiMessage | null>(null)
  const [retryKey, setRetryKey] = useState(0)
  const [dayPickFor, setDayPickFor] = useState<Program | null>(null)

  useEffect(() => {
    setLoading(true)
    client.programAPI
      .list()
      .then((data) => setPrograms(data || []))
      .catch((err) => setError({ key: 'errors.unknown', cause: err }))
      .finally(() => setLoading(false))
  }, [retryKey])

  const goBack = () => (router.canGoBack() ? router.back() : router.replace('/workouts'))

  const startQuick = () => {
    startSession(defaultWorkoutName(), [])
    router.push('/workouts/active')
  }

  const startFromProgram = (program: Program, day: ProgramDay) => {
    startSession(sessionNameForDay(program, day), activeSessionExercisesForDay(day), program.id, day.id)
    setDayPickFor(null)
    router.push('/workouts/active')
  }

  return (
    <Screen>
      <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={{ paddingBottom: 32 }}>
        <View className="gap-6 py-4">
          <View className="flex-row items-center gap-3">
            <IconButton icon={ArrowLeft} label={t('common.back')} variant="ghost" size="md" onPress={goBack} />
            <AppText variant="title">{t('workouts.start.title')}</AppText>
          </View>

          {/* Active session — resume or discard */}
          {session ? (
            <View className="rounded-2xl border border-warning-500/30 bg-warning-500/10 p-4">
              <View className="mb-4 flex-row items-center gap-3">
                <View className="h-10 w-10 items-center justify-center rounded-xl border border-warning-500/30 bg-warning-500/20">
                  <Timer size={20} color="#f59e0b" />
                </View>
                <View className="flex-1">
                  <AppText variant="bodySemibold" numberOfLines={1}>{session.name}</AppText>
                  <AppText variant="caption" style={{ color: '#f59e0b' }}>{t('workouts.start.inProgress')}</AppText>
                </View>
              </View>
              <View className="flex-row gap-2">
                <Pressable
                  onPress={() => router.push('/workouts/active')}
                  className="flex-1 flex-row items-center justify-center gap-2 rounded-xl bg-brand-500 py-2.5 active:scale-95"
                >
                  <Play size={16} color="#ffffff" />
                  <AppText variant="bodySemibold" color="white">{t('workouts.start.resume')}</AppText>
                </Pressable>
                <Pressable
                  onPress={() => cancelSession()}
                  className="flex-1 flex-row items-center justify-center gap-2 rounded-xl border border-surface-border bg-surface-muted py-2.5 active:scale-95"
                >
                  <Trash2 size={16} color={colors.txMuted} />
                  <AppText variant="bodySemibold" color="secondary">{t('workouts.start.discard')}</AppText>
                </Pressable>
              </View>
            </View>
          ) : null}

          {/* Quick start */}
          <Pressable
            onPress={startQuick}
            className="flex-row items-center gap-4 rounded-2xl border border-brand-500/20 bg-brand-500/10 p-5 active:scale-95"
          >
            <View className="h-12 w-12 items-center justify-center rounded-xl bg-brand-500">
              <Zap size={24} color="#ffffff" />
            </View>
            <View className="flex-1">
              <AppText variant="heading">{t('workouts.start.quick')}</AppText>
              <AppText variant="caption" color="muted" className="mt-0.5">{t('workouts.start.quickHint')}</AppText>
            </View>
            <ChevronRight size={20} color={colors.txMuted} />
          </Pressable>

          {/* Start from Program */}
          <View>
            <View className="mb-3 flex-row items-center gap-2">
              <BookOpen size={16} color={accent} />
              <AppText variant="subheading">{t('workouts.start.fromProgram')}</AppText>
            </View>

            {/* Section-scoped: starting an empty workout does not need this list, so
                only the program picker area is replaced. */}
            {error ? (
              <ErrorState
                size="section"
                title={t('programs.list.loadFailed')}
                message={uiMessage(error)}
                onRetry={() => { setError(null); setRetryKey((k) => k + 1) }}
              />
            ) : null}

            {loading ? (
              <View className="flex-row items-center justify-center gap-2 py-12">
                <ActivityIndicator color={accent} />
                <AppText variant="body" color="muted">{t('workouts.start.loadingPrograms')}</AppText>
              </View>
            ) : error ? (
              // The error above already owns this space. Stacking "No programs yet"
              // under it tells a reader with ten programs both that the load failed and
              // that they have none.
              null
            ) : programs.length === 0 ? (
              <View className="items-center rounded-2xl border border-surface-border bg-surface-raised py-10">
                <BookOpen size={32} color={colors.txMuted} />
                <AppText variant="body" color="muted" className="mt-2">{t('workouts.start.noPrograms')}</AppText>
                <Pressable onPress={() => router.navigate('/programs/new')} className="mt-3 active:opacity-60">
                  <AppText variant="caption" style={{ color: accent }}>{t('workouts.start.createFirst')}</AppText>
                </Pressable>
              </View>
            ) : (
              <View className="gap-2">
                {programs.map((p) => {
                  const dayCount = p.days?.length ?? 0
                  return (
                    <Pressable
                      key={p.id}
                      // onEmpty: a program with zero workout days has nothing to load —
                      // open its detail page (add a day there) instead of a dead tap.
                      onPress={() => pickProgramDay(p, startFromProgram, setDayPickFor, () => router.push(`/programs/${p.id}`))}
                      className="flex-row items-center gap-3 rounded-2xl border border-surface-border bg-surface-raised p-4 active:bg-surface-muted"
                    >
                      <View className="h-10 w-10 items-center justify-center rounded-xl border border-brand-500/20 bg-brand-500/10">
                        <BookOpen size={20} color={accent} />
                      </View>
                      <View className="flex-1">
                        <AppText variant="bodySemibold" numberOfLines={1}>{p.name}</AppText>
                        <AppText variant="caption" color="muted" className="mt-0.5">
                          {dayCount > 0 ? t('common.count.days', { count: dayCount }) : t('workouts.start.noDays')}
                        </AppText>
                      </View>
                      <Play size={16} color={accent} />
                    </Pressable>
                  )
                })}
              </View>
            )}
          </View>
        </View>
      </ScrollView>

      <DayPickerSheet program={dayPickFor} onSelect={startFromProgram} onClose={() => setDayPickFor(null)} />
    </Screen>
  )
}