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.

26.6 KB
Raw Blame
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { ActivityIndicator, FlatList, Pressable, RefreshControl, Text, View } from 'react-native'
import { useFocusEffect } from 'expo-router'
import * as Haptics from 'expo-haptics'
import {
  Activity, ArrowDown, ArrowUp, Calendar, Minus, Scale, Sunrise,
  TrendingDown, TrendingUp, X,
} from 'lucide-react-native'
import { uiMessage, useAsyncAction, dayToInstant, daysAgoStr, displayToLbs, displayWeight, maxWeight, todayStr, weightError, weightShort, type WeightLog, type WeightStats, entryDay, dayToLocalDate, BODYWEIGHT_STEP, clampStep, formatDay, formatDate, useTranslation, type UiMessage } from '@lyftr/shared'
import { Alert,
  AppText, BarbellBroken, Button, Card, DateInput, ErrorState, Field, Label, NumberField, NumericKeyboardAccessory,
  NUMERIC_ACCESSORY_ID, PageHeader, Screen, SegmentedControl, Skeleton, StatFailure, StepperTile,
} from '../../../src/components/ui'
import { ExerciseHistoryChart, type ChartPoint } from '../../../src/components/workouts/ExerciseHistoryChart'
import { WeightEntryRow } from '../../../src/components/weight/WeightEntryRow'
import { WeightSkeleton } from '../../../src/components/weight/WeightSkeleton'
import { useServerInfiniteList } from '../../../src/hooks/useServerInfiniteList'
import { client, useSettingsStore } from '../../../src/lib/lyftr'
import { semanticInk } from '../../../src/theme/theme'
import { useTheme } from '../../../src/theme/useTheme'

const PERIODS = ['7d', '30d', '90d', 'All'] as const
type Period = typeof PERIODS[number]
const PERIOD_DAYS: Record<Period, number | null> = { '7d': 7, '30d': 30, '90d': 90, 'All': null }

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

  const [period, setPeriod] = useState<Period>('30d')
  const [stats, setStats] = useState<WeightStats | null>(null)
  // The value the weight box was rejected for, not the sentence: the sentence is made at
  // render, so a banner already on screen follows a language switch.
  const [badWeight, setBadWeight] = useState<number | null>(null)

  // Paginated history list (newest-first) — the FlatList data.
  const fetcher = useCallback((offset: number, limit: number) => client.weightAPI.list({ offset, limit }), [])
  const {
    items, loadMore, hasMore, loading, initialLoading, reload,
    error: listError, retry: retryList,
  } = useServerInfiniteList<WeightLog>({ fetcher })

  // Chart data — a separate period-scoped fetch (uncapped at 1000), re-fetched when the
  // period changes and after every successful log.
  const [chartLogs, setChartLogs] = useState<WeightLog[]>([])
  // Which window chartLogs answers. A failed refetch keeps the series on screen, and
  // that is right when it is the same question asked again — but tapping 90d and
  // failing would otherwise leave 30d's numbers under a 90d label, which is not stale
  // data, it is the wrong answer. Kept here so the screen can tell those apart.
  const [chartPeriod, setChartPeriod] = useState<Period | null>(null)
  // In flight for the window now selected. Without this the provenance rule above reads
  // as an answer: the figures went to "—" and the chart to "No data for this period"
  // while the request for that period was still on the wire.
  const [chartLoading, setChartLoading] = useState(true)

  // Both reads used to swallow their failure, so the figures below fell back to 0 and
  // the screen rendered measurements it had never received.
  const [chartError, setChartError] = useState<UiMessage | null>(null)
  const [statsError, setStatsError] = useState<UiMessage | null>(null)

  // Only the latest request may write. A wider window is a slower query, so tapping All
  // then 7d can land All's answer last, and every figure would then describe a period
  // the user is not looking at. chartLogs is left alone on failure: a failed refetch
  // keeps the series already on screen.
  const chartRequest = useRef(0)
  // Returns the fetch promise so pull-to-refresh can await a full refresh.
  const refetchChart = useCallback(() => {
    const id = ++chartRequest.current
    setChartLoading(true)
    const days = PERIOD_DAYS[period]
    const from = days != null ? daysAgoStr(days) : undefined
    return client.weightAPI.list({ limit: 1000, from })
      .then((data) => {
        if (id !== chartRequest.current) return
        setChartLogs(data || [])
        setChartPeriod(period)
        setChartError(null)
      })
      .catch((err) => { if (id === chartRequest.current) setChartError({ key: 'weight.errors.trendFailed', cause: err }) })
      .finally(() => { if (id === chartRequest.current) setChartLoading(false) })
  }, [period])
  useEffect(() => { refetchChart() }, [refetchChart])

  const statsRequest = useRef(0)
  const refetchStats = useCallback(() => {
    const id = ++statsRequest.current
    return client.weightAPI.stats()
      .then((data) => { if (id === statsRequest.current) { setStats(data); setStatsError(null) } })
      .catch((err) => { if (id === statsRequest.current) setStatsError({ key: 'weight.errors.statsFailed', cause: err }) })
  }, [])
  useEffect(() => {
    fetchSettings()
    refetchStats()
  }, [fetchSettings, refetchStats])

  // Every screen refresh means "this screen's data is stale" across all three sources
  // (history list + stats + chart) — one awaitable callback so they can't drift apart.
  const refreshAll = useCallback(
    () => Promise.all([reload(), refetchStats(), refetchChart()]),
    [reload, refetchStats, refetchChart]
  )

  // One control puts all three reads back, so nobody has to work out which failed.
  // retryList, not reload: a failed later page is resumed rather than re-fetched from 0.
  const [retrying, setRetrying] = useState(false)
  const [heldPageError, setHeldPageError] = useState<string | null>(null)
  // What the page-level error is saying right now, readable from retryAll, which runs
  // before this render's derived values exist.
  const pageErrorRef = useRef<string | null>(null)
  const retryAll = () => {
    if (retrying) return
    setHeldPageError(pageErrorRef.current)
    setRetrying(true)
    retryList()
    Promise.all([refetchStats(), refetchChart()]).finally(() => {
      setRetrying(false)
      setHeldPageError(null)
    })
  }

  // Pull-to-refresh: drive the native RefreshControl spinner off a full refresh.
  const [pulling, setPulling] = useState(false)
  const onPullRefresh = useCallback(async () => {
    setPulling(true)
    await refreshAll()
    setPulling(false)
  }, [refreshAll])

  // Log form
  const [newWeight, setNewWeight] = useState('')
  const [newDate, setNewDate] = useState(todayStr())
  const [newNotes, setNewNotes] = useState('')
  const [showNotes, setShowNotes] = useState(false)
  const [showDuplicateWarning, setShowDuplicateWarning] = useState(false)
  const duplicateWarningDismissedRef = useRef(false)

  // Prefill the input once with the latest entry's weight (so re-logging a similar value
  // is a one-tap edit). Fires only after the first page lands.
  const prefillDoneRef = useRef(false)
  useEffect(() => {
    if (!prefillDoneRef.current && items.length > 0) {
      setNewWeight(String(displayWeight(items[0].weight, unit)))
      prefillDoneRef.current = true
    }
  }, [items, unit])

  // The list is kept mounted under the detail screen, so an edit/delete there doesn't
  // remount us — refetch everything on re-focus instead. Skip the first focus: the
  // hooks/effects above already fetched.
  const focusedOnce = useRef(false)
  useFocusEffect(
    useCallback(() => {
      if (!focusedOnce.current) {
        focusedOnce.current = true
        return
      }
      refreshAll()
    }, [refreshAll])
  )

  // Oldest → newest for the chart. Weight in the display unit; `sub` feeds the tap bubble.
  const chartData: ChartPoint[] = useMemo(
    () =>
      // Same provenance rule as the figures: a series fetched for another window is not
      // this window's trend, however recent it is.
      (chartPeriod === period ? [...chartLogs] : []).reverse().map((l) => {
        const d = dayToLocalDate(entryDay(l))
        return { date: formatDate(d, 'numericMonthDay'), weight: displayWeight(l.weight, unit), sub: formatDate(d, 'monthDayYear') }
      }),
    [chartLogs, chartPeriod, period, unit, i18n.language]
  )
  const [chartWidth, setChartWidth] = useState(0)

  const log = useAsyncAction(async (w: number) => {
        const real = await client.weightAPI.log({
          weight: displayToLbs(w, unit),
          notes: newNotes.trim(),
          logged_at: dayToInstant(newDate),
        })
        Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})
        setNewWeight(String(displayWeight(real.weight, unit)))
        setNewNotes('')
        setNewDate(todayStr())
        setShowNotes(false)
        duplicateWarningDismissedRef.current = false
        refreshAll()
  }, t('weight.log.failed'))

  const handleLog = async () => {
    if (log.busy) return
    const w = parseFloat(newWeight)
    const wErr = weightError(w, unit)
    if (wErr) {
      setBadWeight(w)
      return
    }

    // Guard against a same-day double-log (unless already waved through).
    if (!duplicateWarningDismissedRef.current && items.length > 0 && entryDay(items[0]) === newDate) {
      setShowDuplicateWarning(true)
      return
    }

    setBadWeight(null)
    setShowDuplicateWarning(false)
    void log.run(w)
  }

  if (initialLoading) return <WeightSkeleton />

  // Period stats computed from chartLogs (period-scoped server fetch). For "All" prefer
  // the server-computed aggregate since it isn't capped at 1000.
  // Values only count for the period they were fetched for.
  const periodValues = chartPeriod === period ? chartLogs.map((l) => l.weight) : [] // raw lbs, newest first
  const useServerAggregate = period === 'All' && stats != null
  const currentLbs = periodValues[0] ?? stats?.latest ?? items[0]?.weight ?? 0
  const oldestLbs = periodValues[periodValues.length - 1] ?? stats?.starting ?? currentLbs
  const changeLbs = currentLbs - oldestLbs
  const avgLbs = useServerAggregate
    ? stats!.avg ?? 0
    : periodValues.length > 0
      ? periodValues.reduce((a, b) => a + b, 0) / periodValues.length
      : 0
  const minLbs = useServerAggregate ? stats!.min ?? 0 : periodValues.length > 0 ? Math.min(...periodValues) : 0
  const maxLbs = useServerAggregate ? stats!.max ?? 0 : periodValues.length > 0 ? Math.max(...periodValues) : 0

  // The window selected has not been answered yet: not empty, not unknown, pending.
  const chartPending = chartLoading && chartPeriod !== period

  // Scope the error to the scope of the failure: three reads failing because the server
  // is down is one problem, and gets one error with one retry.
  const loadFailed = chartError != null || statsError != null || listError != null
  const everythingFailed = chartError != null && statsError != null && listError != null
    && items.length === 0 && periodValues.length === 0
  // Hold the page error across a retry. retryList clears its error the moment it is
  // called, so without this the screen tore itself down into a half-broken one for as
  // long as the requests took, then rebuilt the same error.
  const pageError = everythingFailed
    ? (listError ?? (chartError ? uiMessage(chartError) : statsError ? uiMessage(statsError) : ''))
    : retrying
      ? heldPageError
      : null
  pageErrorRef.current = pageError

  // A number we never received is not zero, and neither is the average of nothing: with
  // no values the tiles read "—" on a new account and the failure mark on an outage.
  const currentKnown = periodValues.length > 0 || stats != null || items.length > 0
  const changeKnown = periodValues.length > 1
  // The tiles have exactly one source — the server aggregate on All, the trend read
  // otherwise — so only that read's failure can explain them. Blaming either read let a
  // failed trend beside a healthy stats call render 0 lb and claim it was stale data.
  const tilesError = useServerAggregate ? statsError : chartError
  const noValues = useServerAggregate ? stats!.total_entries === 0 : periodValues.length === 0
  const figuresFailed = noValues && tilesError != null
  const aggregatesUnknown = noValues && !figuresFailed
  // We hold values, but the refresh that would have updated them failed. Keep them and
  // say so — nothing else on screen tells the reader these numbers are out of date.
  const figuresStale = !noValues && tilesError != null

  const current = displayWeight(currentLbs, unit)
  const change = displayWeight(changeLbs, unit)
  const avg = displayWeight(avgLbs, unit)
  const min = displayWeight(minLbs, unit)
  const max = displayWeight(maxLbs, unit)

  const TrendIcon = change === 0 ? Minus : change < 0 ? TrendingDown : TrendingUp
  // Weight loss is framed positive (green); gain negative (red); flat is muted.
  const trendPill =
    change === 0
      ? 'bg-surface-muted border-surface-border'
      : change < 0
        ? 'bg-success-500/10 border-success-500/20'
        : 'bg-error-500/10 border-error-500/20'
  const trendText = change === 0 ? colors.txMuted : change < 0 ? brand.successSoft : brand.errorSoft
  const changeKey = change === 0 ? 'weight.hero.changeNone' : change < 0 ? 'weight.hero.changeLost' : 'weight.hero.changeGained'

  const statCards = [
    { id: 'avg' as const, value: avg, icon: Activity, color: accent },
    { id: 'low' as const, value: min, icon: ArrowDown, color: brand.successSoft },
    { id: 'high' as const, value: max, icon: ArrowUp, color: brand.errorSoft },
  ]
  const periodOptions = PERIODS.map((p) => ({ value: p, label: t(`weight.period.chip.${p}`) }))
  const error = badWeight == null ? null : weightError(badWeight, unit)

  // Title and subtitle stay so the reader knows where they are; the unit chip does not,
  // and neither does the log form — a save that cannot succeed would outrank the retry.
  if (pageError != null) {
    return (
      <Screen>
        <View className="flex-1 gap-5 py-4">
          <PageHeader title={t('weight.title')} subtitle={t('weight.subtitle')} />
          <ErrorState
            size="page"
            title={t('weight.loadFailed')}
            message={pageError}
            onRetry={retryAll}
            retrying={retrying}
          />
        </View>
      </Screen>
    )
  }

  return (
    <Screen>
      <FlatList
        data={items}
        keyExtractor={(l) => String(l.id)}
        showsVerticalScrollIndicator={false}
        contentContainerStyle={{ paddingBottom: 32 }}
        keyboardShouldPersistTaps="handled"
        keyboardDismissMode="on-drag"
        onEndReached={loadMore}
        onEndReachedThreshold={0.5}
        refreshControl={
          <RefreshControl refreshing={pulling} onRefresh={onPullRefresh} tintColor={accent} colors={[accent]} />
        }
        ListHeaderComponent={
          <View className="gap-5 py-4">
            <PageHeader
              title={t('weight.title')}
              subtitle={t('weight.subtitle')}
              action={
                <View className="flex-row items-center gap-1.5 rounded-full border border-brand-500/25 bg-brand-500/10 px-3 py-1">
                  <Calendar size={12} color={accent} />
                  <AppText variant="caption" color="brand">{wUnit}</AppText>
                </View>
              }
            />

            {/* Quick log — kept at the top so entry is reachable on first paint. */}
            <Card>
              <View className="mb-3 flex-row items-center justify-between">
                <View className="flex-row items-center gap-2">
                  <Scale size={16} color={accent} />
                  <AppText variant="bodySemibold">{t('weight.log.title')}</AppText>
                </View>
                {items.length > 0 ? (
                  <AppText variant="caption" color="muted">
                    {t('weight.log.last', { weight: displayWeight(items[0].weight, unit), unit: wUnit })}
                  </AppText>
                ) : null}
              </View>

              <View className="gap-3">
                <StepperTile
                  icon={Scale}
                  label={t('common.weightWithUnit', { unit: wUnit })}
                  name={t('common.weightName')}
                  step={BODYWEIGHT_STEP}
                  onStep={(d) => setNewWeight(String(clampStep(parseFloat(newWeight) || 0, d, { min: 0, max: maxWeight(unit) })))}
                >
                  <NumberField
                    inputMode="decimal"
                    value={newWeight}
                    onChange={setNewWeight}
                    placeholder="0"
                    accessibilityLabel={t('weight.log.weightField')}
                    inputAccessoryViewID={NUMERIC_ACCESSORY_ID}
                  />
                </StepperTile>

                {showNotes ? (
                  <View className="gap-2 rounded-xl border border-surface-border bg-surface-overlay p-3">
                    <View className="mb-1 flex-row items-center justify-between">
                      <AppText variant="caption" color="secondary">{t('weight.log.dateAndNote')}</AppText>
                      <Pressable onPress={() => setShowNotes(false)} hitSlop={8} className="p-1 active:opacity-60" accessibilityLabel={t('weight.log.collapse')}>
                        <X size={14} color={colors.txMuted} />
                      </Pressable>
                    </View>
                    <DateInput value={newDate} onChange={setNewDate} maximumDate={new Date()} />
                    <Field
                      value={newNotes}
                      onChangeText={setNewNotes}
                      placeholder={t('weight.log.notePlaceholder')}
                      maxLength={200}
                    />
                  </View>
                ) : (
                  <Pressable
                    onPress={() => setShowNotes(true)}
                    className="h-11 flex-row items-center justify-center gap-2 rounded-xl border border-surface-border bg-surface-overlay active:scale-[0.99]"
                  >
                    <Calendar size={16} color={colors.txMuted} />
                    <AppText variant="body" color="secondary">{t('weight.log.addDateAndNote')}</AppText>
                  </Pressable>
                )}

                {error || log.error ? (
                  <Alert variant="error" size="compact">{error || log.error}</Alert>
                ) : null}

                {showDuplicateWarning && items.length > 0 ? (
                  <Alert
                    variant="warning"
                    actions={[
                      { label: t('common.cancel'), onPress: () => setShowDuplicateWarning(false) },
                      {
                        label: t('weight.logAnyway'),
                        primary: true,
                        onPress: () => {
                          duplicateWarningDismissedRef.current = true
                          setShowDuplicateWarning(false)
                          handleLog()
                        },
                      },
                    ]}
                  >
                    {t('weight.duplicateWarning', { date: formatDay(entryDay(items[0]), 'monthDay'), weight: displayWeight(items[0].weight, unit), unit: wUnit })}
                  </Alert>
                ) : null}

                <Button
                  title={log.busy ? t('weight.log.submitting') : t('weight.log.submit')}
                  onPress={handleLog}
                  loading={log.busy}
                  disabled={!(parseFloat(newWeight) > 0) || log.busy}
                />
                <View className="flex-row items-center justify-center gap-1.5">
                  <Sunrise size={14} color={brand.warningSoft} />
                  <AppText variant="caption" color="muted">{t('weight.log.tip')}</AppText>
                </View>
              </View>
            </Card>

            {/* Current-weight hero */}
            <Card className="border-brand-500/20 bg-brand-500/5">
              {items.length === 0 && loadFailed ? (
                // Empty and unreachable look identical from here, so the empty copy
                // cannot be the default: it told someone with years of entries they had
                // never weighed themselves.
                <ErrorState
                  title={t('weight.loadFailed')}
                  message={listError ?? (chartError ? uiMessage(chartError) : statsError ? uiMessage(statsError) : '')}
                  onRetry={retryAll}
                  retrying={retrying}
                />
              ) : items.length === 0 ? (
                <View className="items-center py-2">
                  <Label className="mb-1">{t('weight.hero.current')}</Label>
                  <AppText variant="body" color="muted">{t('weight.hero.empty')}</AppText>
                </View>
              ) : (
                <>
                  <View className="flex-row items-start justify-between">
                    <View>
                      <Label className="mb-2">{t('weight.hero.current')}</Label>
                      <View className="flex-row items-end gap-2">
                        <AppText variant="display" style={{ fontSize: 40, lineHeight: 44, fontVariant: ['tabular-nums'] }}>{currentKnown ? current : '—'}</AppText>
                        {currentKnown ? <AppText variant="body" color="muted" className="mb-1.5">{wUnit}</AppText> : null}
                      </View>
                    </View>
                    {changeKnown ? (
                      <View className={`flex-row items-center gap-1.5 rounded-lg border px-3 py-1.5 ${trendPill}`}>
                        <TrendIcon size={16} color={trendText} />
                        <Text className="font-sans-semibold text-sm" style={{ color: trendText, fontVariant: ['tabular-nums'] }}>
                          {Math.abs(change)} {wUnit}
                        </Text>
                      </View>
                    ) : null}
                  </View>
                  {changeKnown ? (
                    <AppText variant="caption" color="muted" className="mt-3">
                      {t(changeKey, { amount: Math.abs(change), unit: wUnit, period: t(`weight.period.span.${period}`) })}
                    </AppText>
                  ) : null}
                </>
              )}
            </Card>

            {/* Stats row */}
            <View className="flex-row gap-3">
              {statCards.map((s) => (
                <Card key={s.id} className="flex-1" style={{ paddingHorizontal: 12 }}>
                  <View className="mb-2 flex-row items-center gap-1.5">
                    <s.icon size={14} color={s.color} />
                    <Label numberOfLines={1}>{t(`weight.stats.${s.id}.label`)}</Label>
                  </View>
                  {chartPending ? (
                    <Skeleton width={56} height={22} />
                  ) : figuresFailed ? (
                    <StatFailure label={t(`weight.stats.${s.id}.failed`)} />
                  ) : (
                    <View className="flex-row items-end gap-1">
                      <AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{aggregatesUnknown ? '—' : Math.round(s.value)}</AppText>
                      {aggregatesUnknown ? null : <AppText variant="caption" color="muted" className="mb-0.5">{wUnit}</AppText>}
                    </View>
                  )}
                </Card>
              ))}
            </View>

            {figuresStale ? (
              <View className="flex-row flex-wrap items-center gap-2 px-1" accessibilityLiveRegion="polite">
                {/* The same mark every other failure on this screen uses, in warning ink
                    rather than error: these numbers are real, just not fresh. */}
                <BarbellBroken size={20} color={semanticInk[isDark ? 'dark' : 'light'].warning} />
                <AppText variant="caption" color="muted">{t('weight.stale')}</AppText>
                <Pressable onPress={retryAll} hitSlop={8} accessibilityRole="button" className="active:opacity-60">
                  <AppText variant="caption" color="secondary" className="underline">{t('common.tryAgain')}</AppText>
                </Pressable>
              </View>
            ) : null}

            {/* Chart + period selector */}
            <Card>
              <View className="mb-3 flex-row items-center justify-between gap-2">
                <AppText variant="bodySemibold">{t('weight.trend.title')}</AppText>
                <View className="flex-1 max-w-[220px]">
                  <SegmentedControl size="sm" options={periodOptions} value={period} onChange={setPeriod} />
                </View>
              </View>
              <View onLayout={(e) => setChartWidth(e.nativeEvent.layout.width)}>
                {chartPending ? (
                  <View className="h-44 justify-center gap-2 px-2">
                    <Skeleton width="100%" height={120} radius={12} />
                  </View>
                ) : chartData.length === 0 && chartError ? (
                  <ErrorState title={t('weight.trend.loadFailed')} message={uiMessage(chartError)} onRetry={retryAll} retrying={retrying} />
                ) : chartData.length < 2 ? (
                  <View className="h-44 items-center justify-center">
                    <AppText variant="body" color="muted">
                      {chartData.length === 0 ? t('weight.trend.noData') : t('weight.trend.needMore')}
                    </AppText>
                  </View>
                ) : (
                  <ExerciseHistoryChart data={chartData} width={chartWidth} unit={wUnit} readoutNote="" height={180} />
                )}
              </View>
            </Card>

            {items.length > 0 ? <Label className="px-1">{t('weight.history.title')}</Label> : null}
          </View>
        }
        renderItem={({ item, index }) => (
          <WeightEntryRow
            item={item}
            next={items[index + 1]}
            unit={unit}
            onDeleted={refreshAll}
          />
        )}
        ListFooterComponent={
          // Only under rows that arrived: with none, the hero above already carries the
          // failure, and saying it twice is two retries for one problem.
          listError && items.length > 0 ? (
            <ErrorState title={t('weight.history.loadMoreFailed')} message={listError} onRetry={retryList} />
          ) : hasMore && loading && items.length > 0 ? (
            <View className="items-center py-3">
              <ActivityIndicator size="small" color={accent} />
            </View>
          ) : undefined
        }
      />
      {/* iOS Done bar above the numeric keyboard (the weight NumberField links it). */}
      <NumericKeyboardAccessory />
    </Screen>
  )
}