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.

5.2 KB
Raw Blame
import React, { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { useZxing } from 'react-zxing'
import { X, AlertCircle } from 'lucide-react'
import { Trans, useTranslation } from '@lyftr/shared'

interface Props {
  onResult: (code: string) => void
  onClose: () => void
}

export default function BarcodeScanner({ onResult, onClose }: Props) {
  const { t } = useTranslation()
  const resolvedRef = useRef(false)
  const [cameraError, setCameraError] = useState<string | null>(null)

  // getUserMedia is a secure-context API, so on a plain-http origin navigator.mediaDevices
  // is undefined and ZXing fails with a raw internal error. Detect it up front and explain
  // the actual cause — the raw message ("Cannot read properties of undefined") tells a
  // self-hoster nothing about what to change. Checked, not caught, because the failure
  // shape varies by browser.
  const insecureContext = typeof window !== 'undefined' && !window.isSecureContext

  const { ref } = useZxing({
    constraints: {
      audio: false,
      video: { facingMode: 'environment' },
    },
    timeBetweenDecodingAttempts: 150,
    onDecodeResult(result) {
      if (resolvedRef.current) return
      resolvedRef.current = true
      navigator.vibrate?.(100)
      onResult(result.getText())
    },
    onError(err) {
      const msg = (err as any)?.message ?? String(err)
      // ZXing fires NotFoundException on every frame with no barcode — ignore those
      if (!msg.includes('NotFoundException') && !msg.includes('No MultiFormat')) {
        setCameraError(msg)
      }
    },
  })

  useEffect(() => {
    const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [onClose])

  return createPortal(
    <div className="fixed inset-0 z-50 bg-black/95 flex flex-col">
      <div className="flex items-center justify-between p-4">
        <p className="text-white text-sm font-medium">{t('food.scan.title')}</p>
        <button
          onClick={onClose}
          className="p-2 rounded-lg hover:bg-white/10 transition-colors"
          aria-label={t('food.scan.close')}
        >
          <X className="w-5 h-5 text-white" />
        </button>
      </div>

      <div className="flex-1 flex items-center justify-center relative">
        {/* Failure states live inside the flex-1 area so they centre. Rendering them below
            it left an empty stretched container that pushed the text onto the tab bar. */}
        {insecureContext ? (
          <div className="flex flex-col items-center gap-3 px-6 text-center">
            <AlertCircle className="w-8 h-8 text-error-400" />
            <p className="text-white text-sm font-medium">{t('food.scan.httpsTitle')}</p>
            <p className="text-white/60 text-xs leading-relaxed">
              <Trans
                i18nKey="food.scan.httpsBody"
                components={{ mono: <span className="font-mono" /> }}
              />
            </p>
            <button onClick={onClose} className="btn-primary btn-sm mt-2">
              {t('food.scan.searchByName')}
            </button>
          </div>
        ) : cameraError ? (
          <div className="flex flex-col items-center gap-3 px-6 text-center">
            <AlertCircle className="w-8 h-8 text-error-400" />
            <p className="text-white text-sm font-medium">{t('food.scan.unavailable')}</p>
            <p className="text-white/50 text-xs font-mono break-all">{cameraError}</p>
            <button onClick={onClose} className="btn-primary btn-sm mt-2">
              {t('food.scan.searchByName')}
            </button>
          </div>
        ) : null}

        {!cameraError && !insecureContext && (
          <video
            // react-zxing ref type doesn't match HTMLVideoElement exactly; cast is safe as useZxing always returns a video ref
            ref={ref as React.RefObject<HTMLVideoElement>}
            className="w-full max-w-sm rounded-lg"
            style={{ maxHeight: '60vh', objectFit: 'cover' }}
            playsInline
          />
        )}

        {!cameraError && !insecureContext && (
          <div className="absolute pointer-events-none" style={{ width: 260, height: 160 }}>
            <div className="absolute top-0 left-0 w-8 h-8 border-t-2 border-l-2 border-brand-400 rounded-tl" />
            <div className="absolute top-0 right-0 w-8 h-8 border-t-2 border-r-2 border-brand-400 rounded-tr" />
            <div className="absolute bottom-0 left-0 w-8 h-8 border-b-2 border-l-2 border-brand-400 rounded-bl" />
            <div className="absolute bottom-0 right-0 w-8 h-8 border-b-2 border-r-2 border-brand-400 rounded-br" />
            <div
              className="absolute inset-x-0 h-0.5 bg-brand-400/70"
              style={{ animation: 'barcode-scan 1.5s ease-in-out infinite' }}
            />
          </div>
        )}
      </div>

      {!insecureContext && !cameraError && (
        <p className="text-center text-white/60 text-xs pb-8 px-4">
          {t('food.scan.hint')}
        </p>
      )}

      <style>{`
        @keyframes barcode-scan {
          0%   { top: 10%; }
          50%  { top: 85%; }
          100% { top: 10%; }
        }
      `}</style>
    </div>,
    document.body,
  )
}