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.3 KB
Raw Blame
import { useState, useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import { X, Scale, Save, AlertCircle, Calendar, FileText } from 'lucide-react'
import { weightAPI } from '../services/api'
import { useSettingsStore, weightShort, displayToLbs , weightError, maxWeight } from '../stores/settings'
import { useBodyScrollLock } from '../hooks/useBodyScrollLock'
import { useEscapeKey } from '../hooks/useEscapeKey'
import { useAsyncAction, todayStr, dayToInstant, entryDay, BODYWEIGHT_STEP, clampStep, useTranslation, types } from '@lyftr/shared'
import StepperTile from './ui/StepperTile'
import NumberField from './ui/NumberField'

interface Props {
  isOpen: boolean
  lastValue: number | null
  lastLog?: types.WeightLog | null
  onClose: () => void
  onSuccess: (log: types.WeightLog) => void
}

export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose, onSuccess }: Props) {
  const { t } = useTranslation()
  const { settings } = useSettingsStore()
  const wUnit = weightShort(settings.weight_unit)

  const [value, setValue] = useState('')
  const [date, setDate] = useState(todayStr())
  const [notes, setNotes] = useState('')
  const [showExtras, setShowExtras] = useState(false)
  // The rejected weight, not the sentence about it: the text is made at render from the current
  // unit and language, so a banner already on screen follows a switch of either.
  const [rejected, setRejected] = useState<number | null>(null)
  const [showDuplicateWarning, setShowDuplicateWarning] = useState(false)
  const duplicateWarningDismissedRef = useRef(false)
  const formRef = useRef<HTMLFormElement>(null)

  useEffect(() => {
    if (!isOpen) return
    setValue(lastValue && lastValue > 0 ? String(lastValue) : '')
    setDate(todayStr())
    setNotes('')
    setShowExtras(false)
    setRejected(null)
    setShowDuplicateWarning(false)
    duplicateWarningDismissedRef.current = false
  }, [isOpen, lastValue])

  const save = useAsyncAction(async (w: number) => {
    const log = await weightAPI.log({
      weight: displayToLbs(w, settings.weight_unit),
      notes: notes.trim(),
      logged_at: dayToInstant(date),
    })
    onSuccess(log)
    onClose()
  }, t('common.saveFailed'))

  const handleClose = () => { setRejected(null); onClose() }

  useBodyScrollLock(isOpen)
  useEscapeKey(isOpen, handleClose)

  if (!isOpen) return null

  const error = rejected === null ? '' : weightError(rejected, settings.weight_unit) ?? ''

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (save.busy) return
    const w = parseFloat(value)
    const wErr = weightError(w, settings.weight_unit)
    if (wErr) {
      setRejected(w)
      return
    }

    if (!duplicateWarningDismissedRef.current && lastLog && entryDay(lastLog) === date) {
      setShowDuplicateWarning(true)
      return
    }

    setRejected(null)
    setShowDuplicateWarning(false)
    void save.run(w)
  }

  return createPortal((
    <div
      className="fixed inset-0 bg-black/60 z-[70] flex items-end sm:items-center justify-center p-0 sm:p-4"
      onClick={handleClose}
    >
      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby="qws-title"
        className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-md max-h-[90vh] overflow-y-auto animate-slide-up"
        onClick={e => e.stopPropagation()}
      >
        {/* Drag handle — mobile only */}
        <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mt-3 mb-1 sm:hidden" />

        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b border-surface-border">
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-lg bg-brand-500/10 border border-brand-500/20 flex items-center justify-center">
              <Scale className="w-4 h-4 text-brand-500" />
            </div>
            <h2 id="qws-title" className="font-display font-bold text-lg text-tx-primary">{t('home.quickWeighIn.title')}</h2>
          </div>
          <button onClick={handleClose} className="p-1.5 hover:bg-surface-muted rounded-lg transition-colors">
            <X className="w-5 h-5 text-tx-muted" />
          </button>
        </div>

        <form ref={formRef} onSubmit={handleSubmit} className="p-5 space-y-4">
          {(error || save.error) && (
            <div className="alert-error" role="alert" aria-live="polite">
              <AlertCircle className="w-4 h-4 flex-shrink-0" />
              <span>{error || save.error}</span>
            </div>
          )}

          {showDuplicateWarning && lastLog && (
            <div className="flex items-start gap-3 rounded-xl border border-amber-500/20 bg-amber-500/10 px-4 py-3 text-sm text-amber-400" role="alert">
              <AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
              <div className="flex-1 min-w-0">
                <p className="font-medium">{t('home.quickWeighIn.duplicateToday', { weight: Math.round(lastValue ?? 0), unit: wUnit })}</p>
                <div className="flex gap-2 mt-2">
                  <button
                    type="button"
                    onClick={() => setShowDuplicateWarning(false)}
                    className="px-3 py-1 rounded-lg text-xs font-medium bg-surface-overlay border border-surface-border text-tx-secondary hover:text-tx-primary transition-colors"
                  >
                    {t('common.cancel')}
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      duplicateWarningDismissedRef.current = true
                      setShowDuplicateWarning(false)
                      formRef.current?.requestSubmit()
                    }}
                    className="px-3 py-1 rounded-lg text-xs font-medium bg-amber-500/20 border border-amber-500/30 text-amber-300 hover:bg-amber-500/30 transition-colors"
                  >
                    {t('weight.logAnyway')}
                  </button>
                </div>
              </div>
            </div>
          )}

          <StepperTile
            icon={Scale}
            label={t('common.weightWithUnit', { unit: wUnit })}
            name={t('common.weightName')}
            step={BODYWEIGHT_STEP}
            onStep={d => setValue(String(clampStep(parseFloat(value) || 0, d, { max: maxWeight(settings.weight_unit) })))}
          >
            <NumberField value={value} onChange={setValue} autoFocus aria-label={t('home.quickWeighIn.weight')} />
          </StepperTile>

          {!showExtras ? (
            <button
              type="button"
              onClick={() => setShowExtras(true)}
              className="text-xs text-brand-400 hover:text-brand-300 transition-colors flex items-center gap-1"
            >
              {t('home.quickWeighIn.changeDateOrNote')}
            </button>
          ) : (
            <div className="space-y-3 pt-1">
              <div>
                <label className="label">
                  <Calendar className="w-3 h-3" /> {t('home.quickWeighIn.date')}
                </label>
                <input
                  type="date"
                  value={date}
                  onChange={e => setDate(e.target.value)}
                  max={todayStr()}
                  className="input mt-1"
                />
              </div>
              <div>
                <label className="label">
                  <FileText className="w-3 h-3" /> {t('home.quickWeighIn.note')} <span className="text-tx-muted font-normal normal-case tracking-normal">{t('home.quickWeighIn.optional')}</span>
                </label>
                <input
                  type="text"
                  value={notes}
                  onChange={e => setNotes(e.target.value)}
                  placeholder={t('weight.notePlaceholder')}
                  maxLength={200}
                  className="input mt-1"
                />
              </div>
            </div>
          )}

          <button
            type="submit"
            disabled={!(parseFloat(value) > 0) || save.busy}
            className="btn-primary btn-lg w-full"
          >
            <Save className="w-4 h-4" />
            {save.busy ? t('common.saving') : t('common.save')}
          </button>
        </form>
      </div>
    </div>
  ), document.body)
}