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.

14.8 KB
Raw Blame
import { useCallback, useEffect, useRef, useState } from 'react'
import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from 'react-native'
import { router, useFocusEffect, type Href } from 'expo-router'
import { Award, CheckCircle2, ChevronRight, Dumbbell, Library, Plus, RotateCcw, TrendingUp } from 'lucide-react-native'
import { format } from 'date-fns'
import { weightShort, workoutDay, useTranslation, type Workout } from '@lyftr/shared'
import { AppText, Card, EmptyState, ErrorState, IconButton, StatFailure, Label, PageHeader, Screen, SearchField, Toast } from '../../../src/components/ui'
import { WorkoutCard } from '../../../src/components/workouts/WorkoutCard'
import { WorkoutsSkeleton } from '../../../src/components/workouts/WorkoutsSkeleton'
import { useServerInfiniteList } from '../../../src/hooks/useServerInfiniteList'
import { client, useSettingsStore, useWorkoutSession } from '../../../src/lib/lyftr'
import { useWorkoutOutcome } from '../../../src/lib/workoutOutcome'
import { useTheme } from '../../../src/theme/useTheme'

// Cross-tab jump (workouts → programs), same rule as programs/[id]'s handleStart:
// router.navigate, not push, or it corrupts the native tab/back stack.
const programHref = (id: number) => `/programs/${id}` as unknown as Href

export default function Workouts() {
  const { t } = useTranslation()
  const settings = useSettingsStore((s) => s.settings)
  const fetchSettings = useSettingsStore((s) => s.fetch)
  const unit = weightShort(settings.weight_unit)
  const { accent, colors } = useTheme()

  const [search, setSearch] = useState('')
  const [debouncedSearch, setDebouncedSearch] = useState('')

  // Confirmation toast on arrival from a finished/discarded session (the courier is the
  // one-shot useWorkoutOutcome store, set during teardown before we navigate here).
  const outcome = useWorkoutOutcome((s) => s.outcome)
  const clearOutcome = useWorkoutOutcome((s) => s.clear)
  const restoreSession = useWorkoutSession((s) => s.restoreSession)

  useEffect(() => {
    fetchSettings()
  }, [fetchSettings])

  // Debounce search so we don't fire a request on every keystroke. 250ms sits in the
  // research-backed 200–300ms sweet spot (>300ms starts to feel laggy).
  useEffect(() => {
    const t = setTimeout(() => setDebouncedSearch(search), 250)
    return () => clearTimeout(t)
  }, [search])

  const fetcher = useCallback(
    (offset: number, limit: number) =>
      client.workoutAPI.list({ offset, limit, q: debouncedSearch || undefined }),
    [debouncedSearch]
  )
  const {
    items: workouts, loadMore, hasMore, loading, initialLoading, refreshing, reload,
    error: listError, retry: retryList,
  } = useServerInfiniteList<Workout>({ fetcher, deps: [debouncedSearch] })

  // The stack keeps this screen mounted under the detail screen, so a delete made
  // there doesn't remount us the way the web SPA's re-navigation does — refetch on
  // re-focus instead. Skip the first focus: the hook's deps-effect already fetched.
  const focusedOnce = useRef(false)
  useFocusEffect(
    useCallback(() => {
      if (!focusedOnce.current) {
        focusedOnce.current = true
        return
      }
      reload()
    }, [reload])
  )

  // Pull-to-refresh: drive the native RefreshControl spinner off the reload promise.
  // Which query the rows on screen answer. Keeping the previous results while a new
  // search runs is right — until that search fails, at which point the field says one
  // thing and the rows below it another. Then they are not stale, they are a different
  // query's answer, and the error takes their place.
  const [answeredQuery, setAnsweredQuery] = useState('')
  // Keyed on the hook's own loading flag, which is already true by the time this runs
  // for a new query — `refreshing` is not, so this marked a query answered before its
  // request had left, and a failure then kept the previous query's rows on screen.
  useEffect(() => {
    if (!loading && listError == null) setAnsweredQuery(debouncedSearch)
  }, [loading, listError, debouncedSearch])
  const queryAnswered = listError == null || answeredQuery === debouncedSearch

  const [pulling, setPulling] = useState(false)
  const onPullRefresh = useCallback(async () => {
    setPulling(true)
    await reload()
    setPulling(false)
  }, [reload])

  // Skeleton (not the barbell loader) for the list's first load: content-shaped
  // placeholders read as faster and match where the real cards will land.
  if (initialLoading) return <WorkoutsSkeleton />

  // Post-session confirmation. Saved = quiet success; discarded = tap-to-undo
  // (restores the exact session snapshot and drops you back into it). Built before the
  // early return so a list that fails to load does not swallow the outcome of a session.
  const outcomeToast = outcome ? (
    outcome.kind === 'saved' ? (
      outcome.progression ? (
        <Toast
          variant={outcome.progression.is_pr ? 'warning' : 'success'}
          icon={outcome.progression.is_pr ? Award : TrendingUp}
          title={outcome.progression.is_pr ? t('workouts.toast.newPr', { name: outcome.progression.program_name }) : t('workouts.toast.newTargets', { name: outcome.progression.program_name })}
          description={t('workouts.toast.reviewUpdates', { count: outcome.progression.count })}
          onPress={() => {
            const programId = outcome.progression!.program_id
            clearOutcome()
            router.navigate(programHref(programId))
          }}
          onDismiss={clearOutcome}
        />
      ) : (
        <Toast
          variant="success"
          icon={CheckCircle2}
          title={t('workouts.toast.saved')}
          description={t('workouts.toast.tapToView')}
          onPress={() => {
            clearOutcome()
            router.push(`/workouts/${outcome.workoutId}`)
          }}
          onDismiss={clearOutcome}
        />
      )
    ) : (
      <Toast
        variant="default"
        icon={RotateCcw}
        title={t('workouts.toast.discarded')}
        description={t('workouts.toast.tapToUndo')}
        onPress={() => {
          restoreSession(outcome.session)
          clearOutcome()
          router.push('/workouts/active')
        }}
        onDismiss={clearOutcome}
      />
    )
  ) : null

  // Nothing arrived, so there is no screen to draw around the failure. One error for the
  // page, under the same title; a later page failing under loaded rows is the footer's.
  //
  // Not while a search is running, though: taking the whole screen takes the field the
  // query was typed into, so the query cannot be cleared or changed and retry can only
  // re-run the request that just failed. A search that fails keeps its search bar.
  if (listError && workouts.length === 0 && !debouncedSearch) {
    return (
      <Screen>
        <View className="flex-1 gap-5 py-4">
          <PageHeader title={t('workouts.list.title')} subtitle={t('workouts.list.subtitle')} />
          <ErrorState size="page" title={t('workouts.list.loadFailed')} message={listError} onRetry={retryList} retrying={loading} />
        </View>
        {outcomeToast}
      </Screen>
    )
  }

  const now = new Date()
  const mayHaveMore = hasMore || listError != null
  // Nothing loaded and the read failed: these tiles have no figure to round down to.
  // "0+ logged" is true of every account that ever existed, which is another way of
  // saying nothing. Reached with a search on screen; otherwise the page error owns this.
  const countsUnknown = listError != null && (workouts.length === 0 || !queryAnswered)
  const month = format(now, 'yyyy-MM')
  const thisMonth = workouts.filter((w) => workoutDay(w).startsWith(month)).length
  const oldestLoadedDay = workouts.length > 0 ? workoutDay(workouts[workouts.length - 1]) : null
  const monthCountKnown = !mayHaveMore || (oldestLoadedDay != null && oldestLoadedDay < `${month}-01`)
  const stats = [
    // These summarize the *loaded* items; while pages remain, the total is a lower bound.
    // A failed page counts as "pages remain": the hook drops hasMore on error, and
    // without listError here a dropped connection made the count look more certain.
    { label: t('workouts.stats.total'), failed: t('workouts.stats.totalFailed'), value: mayHaveMore ? `${workouts.length}+` : String(workouts.length), unit: t('workouts.stats.logged') },
    {
      label: t('workouts.stats.thisMonth'),
      failed: t('workouts.stats.thisMonthFailed'),
      // The month the workout was logged in, not the month its UTC instant lands in —
      // a session near a month boundary belongs to the month the lifter trained in.
      // Newest-first paging means we have seen the whole month only once a loaded row
      // predates it; until then the count is a lower bound and says so, like Total.
      value: monthCountKnown ? String(thisMonth) : `${thisMonth}+`,
      unit: t('workouts.stats.sessions'),
    },
    {
      label: t('workouts.stats.avgTime'),
      failed: t('workouts.stats.avgTimeFailed'),
      value:
        workouts.length > 0
          ? String(Math.round(workouts.reduce((sum, w) => sum + w.duration, 0) / workouts.length / 60))
          : '—',
      unit: t('workouts.stats.min'),
    },
  ]

  return (
    <Screen>
      <FlatList
        data={queryAnswered ? workouts : []}
        keyExtractor={(w) => String(w.id)}
        showsVerticalScrollIndicator={false}
        contentContainerStyle={{ paddingBottom: 32 }}
        keyboardShouldPersistTaps="handled"
        keyboardDismissMode="on-drag"
        // IntersectionObserver-sentinel replacement: fetch the next page as the user
        // nears the end (threshold 0.5 ≈ the web's 200px rootMargin pre-fetch).
        onEndReached={loadMore}
        onEndReachedThreshold={0.5}
        refreshControl={
          <RefreshControl refreshing={pulling} onRefresh={onPullRefresh} tintColor={accent} colors={[accent]} />
        }
        ItemSeparatorComponent={() => <View className="h-3" />}
        ListHeaderComponent={
          <View className="gap-5 py-4">
            <PageHeader
              title={t('workouts.list.title')}
              subtitle={t('workouts.list.subtitle')}
              action={
                <IconButton
                  icon={Plus}
                  label={t('workouts.list.logWorkout')}
                  variant="solid"
                  size="md"
                  onPress={() => router.push('/workouts/new')}
                />
              }
            />

            {/* A labelled row, not a header icon: the exercise library is a place to go, and an
                unlabelled glyph beside the plus did not say where. */}
            <Pressable
              accessibilityRole="button"
              accessibilityLabel={t('workouts.list.browseExercises')}
              onPress={() => router.push('/workouts/exercises')}
              className="flex-row items-center gap-3 rounded-xl border border-surface-border bg-surface-raised p-3.5 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">
                <Library size={20} color={accent} strokeWidth={2} />
              </View>
              <View className="flex-1">
                <AppText variant="bodySemibold">{t('workouts.list.browseExercises')}</AppText>
                <AppText variant="caption" color="muted" numberOfLines={1}>{t('exercises.browse.subtitle')}</AppText>
              </View>
              <ChevronRight size={16} color={colors.txMuted} />
            </Pressable>

            {/* Summary — web's 3-card grid. Dimmed while a new search revalidates: the
                stats summarize the loaded items, so they're stale mid-search — fading
                them (and the rows below) signals "updating" without a blank flash. */}
            <View className="flex-row gap-3" style={{ opacity: refreshing ? 0.5 : 1 }}>
              {/* Tighter horizontal padding than Card's default: three-up columns are
                  narrow and the uppercase wide-tracked label truncates at p-4. */}
              {stats.map((s) => (
                <Card key={s.label} className="flex-1 rounded-2xl" style={{ paddingHorizontal: 12 }}>
                  <Label className="mb-2" numberOfLines={1}>{s.label}</Label>
                  {countsUnknown ? (
                    <StatFailure label={s.failed} />
                  ) : (
                  <View className="flex-row items-end gap-1">
                    <AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>
                      {s.value}
                    </AppText>
                    <AppText variant="caption" color="muted" className="mb-0.5" numberOfLines={1}>
                      {s.unit}
                    </AppText>
                  </View>
                  )}
                </Card>
              ))}
            </View>

            {/* Reusable SearchField: leading search icon + a trailing slot that is a
                spinner while a new query fetches (previous results stay on screen and
                swap in place — no flash-to-zero) or a clear (×) button once there's text. */}
            <SearchField
              value={search}
              onChangeText={setSearch}
              loading={refreshing}
              placeholder={t('workouts.list.searchPlaceholder')}
            />
          </View>
        }
        renderItem={({ item }) => (
          // Fade the stale rows while a new search revalidates (they swap in place when
          // the fresh page lands); the search field above stays full-opacity/interactive.
          <View style={{ opacity: refreshing ? 0.5 : 1 }}>
            <WorkoutCard
              workout={item}
              unit={unit}
              onPress={() => router.push(`/workouts/${item.id}`)}
              onDeleted={() => reload()}
            />
          </View>
        )}
        ListEmptyComponent={
          loading ? undefined : listError ? (
            // Reached only with a search on screen (the early return covers the rest):
            // "No workouts found" would blame the query for a request that never landed.
            <ErrorState title={t('workouts.list.loadFailed')} message={listError} onRetry={retryList} retrying={loading} />
          ) : (
            <EmptyState
              icon={Dumbbell}
              title={t('workouts.list.empty.title')}
              subtitle={search ? t('common.tryDifferentSearch') : t('workouts.list.empty.startHint')}
            />
          )
        }
        ListFooterComponent={
          listError && workouts.length > 0 ? (
            <ErrorState title={t('workouts.list.loadFailed')} message={listError} onRetry={retryList} retrying={loading} />
          ) : hasMore && loading && workouts.length > 0 ? (
            <View className="items-center py-3">
              <ActivityIndicator size="small" color={accent} />
            </View>
          ) : undefined
        }
      />

      {outcomeToast}
    </Screen>
  )
}